Aravind
Aravind

Reputation: 21

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:

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 :

[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");
}

Upvotes: 2

Views: 7456

Answers (1)

Ryan Gates
Ryan Gates

Reputation: 4539

You would not mock the TestClass, because that is what you are testing.

For this to work, you need to make a read-only property for 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.

Your test would look something like the following for testing the Method for the B test case:

[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:

[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. This allows you to have an immutable object that will reduce the state of your application.

Upvotes: 5

Related Questions