c# - 如何最小起订量和重写构造函数?

标签 c# mocking moq

是否可以使用 Moq 库来进行起订量并重写构造函数?

我有一个这样的类(class):

public class A{
    private string _b;
    public A()
    {
        _b = Service.getB();
    }
    public int duplicate(int a){
       return a*2;
    }
}

我想测试方法“duplicate”,但我无法实例化 A 类型的对象,因为我缺少一些依赖项。我可以以某种方式重写/模拟构造函数来创建对象并将其用于测试其他方法吗?

更改应仅应用于测试,我不应更改 A 类

最佳答案

不可能使用 Moq framework 覆盖或模拟构造函数。

即使您尝试创建 TestA 类并从 A 继承它,无参数构造函数仍然会被调用。您可以在以下文章 "Constructors in C#" 中阅读更多内容。还有来自 MSDN 的引用:

If a class contains no instance constructor declarations, a default instance constructor is automatically provided. That default constructor simply invokes the parameterless constructor of the direct base class. If the direct base class does not have an accessible parameterless instance constructor, a compile-time error occurs.

如果确实需要重写构造函数,您可以看看另一个模拟框架(例如 TypeMock 甚至可以模拟静态构造函数)

SO question "What C# mocking framework to use?" 包含一长串模拟框架和演示 "Battle of the mocking frameworks",可以帮助您选择正确的工具。

关于c# - 如何最小起订量和重写构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19931844/

相关文章:

c# - 来自 EventHandler 的 Console.Writeline

c# - 拖动箭头断点时调试范围内的错误

spring - 如何在 JUnit 测试中模拟 TransactionManager(在容器外)?

c# - Moq TargetParameterCountException 与 lambda 表达式

C# 为对象列表创建 Mock Configuration.GetSection (“Section:SubSection” )

c# - 如何验证字典参数?

c# 分解长字符串的最佳方法

c# - MVC 中的自定义表单例份验证

python - 如何在 Sphinx 中模拟 wxPython?

scala - 具有特征的模拟类