简体   繁体   English

测试工厂模式

[英]Testing Factory Pattern

I have the small sample factory pattern implementation below, and was wondering if someone can help me write proper Moq unit test cases, for maximum code coverage: 我下面有一个小的示例工厂模式实现,想知道是否有人可以帮助我编写适当的Moq单元测试用例,以最大程度地覆盖代码:

public class TestClass
{ 
    private readonly IService service;

    public TestClass(Iservice service)
    {
        this.service = service;
    }

    public void Method(string test)
    {
        service = TestMethod(test);
        service.somemethod();
    }

    private IService TestMethod(string test)
    {
        if(test == 'A')
            service = new A();
        if(test == 'B')
            service = new B();
        return service;
    }
}

I am looking for some help in Testing the TestClass and more importantly TestMethod when i send Mock, for example my test method goes below : 当我发送Mock时,我正在寻找一些测试TestClass的帮助,更重要的是TestMethod,例如,我的测试方法如下:

[TestMethod]
public void TestCaseA()
{
    Mock<IService> serviceMock = new Mock<Iservice>(MockBehaviour.strict);
    TestClass tClass = new TestClass(serviceMock.Object);

    // The Question is, what is best approach to test this scenario ?
    // If i go with below approach, new A() will override serviceMock
    // which i am passing through constructor.
    var target = tClass.Method("A");
}

You would not mock the TestClass , because that is what you are testing. 您不会嘲笑TestClass ,因为这就是您要测试的内容。

For this to work, you need to make a read-only property for service . 为此,您需要为service创建一个只读属性。

public IService Service { get; private set; }

You need to test the way that both the constructor and Method modify the state(in this case Service ) of the TestClass instance. 您需要测试构造函数和Method修改TestClass实例的状态(在本例中为Service )的方式。

Your test would look something like the following for testing the Method for the B test case: 您的测试将类似于以下内容,以测试B测试用例的Method

[TestMethod]
public void TestSomeMethod()
{
    // Arrange/Act
    var target = new TestClass((new Mock<IService>()).Object);
    target.Method("B");

    // Assert
    Assert.IsInstanceOfType(target.Service, typeof(B));
}

Your test would look something like the following for testing the constructor for the A test case: 您的测试看起来类似于以下测试A测试用例的构造函数:

[TestMethod()]
public void TestCasesA()
{
    // Arrange/Act
    var target = new TestClass("A");

    // Assert
    Assert.IsInstanceOfType(target.service, typeof(A));
}

I would recommend only using the constructor approach to inject your IService . 我建议仅使用构造函数方法注入IService This allows you to have an immutable object that will reduce the state of your application. 这使您拥有一个不变的对象,该对象将减少应用程序的状态。

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

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