简体   繁体   English

Moq中的抽象工厂单元测试

[英]Abstract Factory Unit Testing In Moq

Suppose I have following class called SomeClass as defined: 假设我定义了以下名为SomeClass类:

public SomeClass
{
    private IThingFactory _thingFactory;

    public SomeClass(IThingFactory thingFactory)
    {
        _thingFactory = thingFactory;
    }

    public IThing CreateThing(int a, int b, string c)
    {
        IThing thing = _thingFactory.MakeEmptyThing();
        thing.MakeFromFields(a, b, c);

        return thing;
    }
}

The spec of the CreateThing(int a, int b, string c) method is that it takes an int a , int b , string c and returns an IThing with the corresponding properties. CreateThing(int a, int b, string c)方法的规范是,它接受一个int a ,int b ,字符串c并返回具有相应属性的IThing (so internally maybe new Thing(a, b, c) ) (因此在内部可能是new Thing(a, b, c)

However the implementation delegates that work to a IThingFactory and Thing populates itself. 但是,实现将工作委托给IThingFactory并且Thing自行填充。

So now I'm trying to unit test the method CreateThing() , but I'm not exactly sure how it should work. 所以现在我试图对方法CreateThing()进行单元测试,但是我不确定该如何工作。

Here's what I tried: 这是我尝试过的:

Based off of the principles of mocking dependencies, I created a Mock<IThingFactory> and gave it to the constructor of SomeClass 基于Mock<IThingFactory>依赖关系的原理,我创建了一个Mock<IThingFactory>并将其提供给SomeClass的构造函数

_mockThingFactory = new Mock<IThingFactory>();
someClass = new SomeClass(_mockThingFactory.Object);

Afterwards, I called the method under test 之后,我调用了被测方法

IThing thing = _someClass.CreateThing(It.IsAny<int>(), 
    It.IsAny<int>(), 
    It.IsAny<string>>());

And to assert, I'm not sure. 而且断言,我不确定。 Should I verify that MakeEmptyThing() was called? 我应该验证是否调用了MakeEmptyThing()吗? What do I do with thing.MakeFromFields(a, b, c); 我该如何处理thing.MakeFromFields(a, b, c); ?

You should look at results of the method under test. 您应该查看被测方法的结果。 In this case result is "factory constructed object and particular method of the object is called with arguments". 在这种情况下,结果是“工厂构造的对象,并且使用参数调用该对象的特定方法”。

To test that you can return mock object from CreateThing and than check if MakeFromFields on it called with expected parameters (ie Using Moq, How to setup a method call with an input parameter as an object with expected property values? ). 要测试您是否可以从CreateThing返回模拟对象,然后检查MakeFromFields上的MakeFromFields是否使用期望的参数调用(即, 使用Moq,如何设置将输入参数作为具有期望的属性值的对象的方法调用? )。

var mockThing = new Mock<IThing>();
_mockThingFactory.Setup(f=> f.MakeEmptyThing()).Returns(mockThing.Object);

classUnderTest =  new SomeClass(_mockThingFactory.Object);  
classUnderTest.CreateThing(1,2,3);
mockThing.Verify(....)

Note that it may be better to move MakeFromFields to factory. 请注意,最好将MakeFromFields移到工厂。 Also consider using existing DI framework (like Unity) to deal with all object creation. 还可以考虑使用现有的DI框架(例如Unity)来处理所有对象的创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM