在单元测试中模拟一个类中的类

时间:2016-12-27 20:06:52

标签: c# unit-testing mocking moq

我在单元测试中有以下代码

using ThirdClass;
public class OtherClass
{
    public void foo()
    {
        ThirdClass third = new ThirdClass();
        third.bar();
    }
}

这是另一个班级

public void TestMethod()
{
    OtherClass other = new OtherClass();
    Mock<ThirdClass> third =  new Mock<ThirdClass>();
    third.setup(o => o.bar()).Returns(/*mock implementation*/);
    /*use third in all instances of ThirdClass in OtherClass*/
    OtherClass.foo();
}

ThirdClass仍处于开发阶段,但我希望能够使用moq运行我的单元测试。有没有办法告诉moq在TestClass中模拟ThirdClass而不使用OtherClass /依赖于moq?理想情况如下:

(with-eval-after-load 'neotree
  (evil-define-key 'evilified neotree-mode-map (kbd "i") 'neotree-previous-line)
  (evil-define-key 'evilified neotree-mode-map (kbd "k") 'neotree-next-line))

2 个答案:

答案 0 :(得分:3)

if (d.value<breaks[0]) { return colours[0]; } for (i=0;i<breaks.length+1;i++){ if (d.value>=breaks[i]&&d.value<breaks[i+1]){ return colours[i]; } } 中的方法foo()不是单元可测试的,因为您创建了实际服务的新实例而无法模拟它。

如果你想模仿它,那么你必须注入OtherClass依赖注入。

ThirdClass的示例将是:

OtherClass

您的测试方法以及测试其他类的示例可以是:

public class OtherClass
{
    private readonly ThirdClass _thirdClass;
    public OtherClass(ThirdClass thirdClass) 
    {
         _thirdClass = thirdClass;
    }
    public void foo()
    {
        _thirdClass.bar();
    }
}

您可以使用示例尝试使用Unity DI容器。

答案 1 :(得分:0)

感谢您的想法,伙计们。我最终创建了另一个版本的OtherClass.foo(),它接受了一个ThirdClass的实例,并且在没有它的版本中创建了一个实例。测试时我可以调用foo(mockThird),但用户可以使用foo()。

using ThirdClass;
public class OtherClass
{
    public void foo(ThirdClass third)
    {
        third.bar();
    }
    public void foo()
    {
        foo(new ThirdClass());
    }
}

在测试课程中

public void TestMethod()
{
    Mock<ThirdClass> third =  new Mock<ThirdClass>();
    third.setup(o => o.bar()).Returns(/*mock implementation*/);
    OtherClass testObject= new OtherClass();

    testObject.foo(third);
}
相关问题