Service Fabric and Dependency Injection, part 3: Unit testing

This is a series of blog posts:

Unit testing of the final construct we’ve got in previous two parts would be challenging due to a number of reasons:

  • Both StatelessServiceContext and StatefulServiceContext are sealed, what means you cannot instantiate them directly, ContainerConfig(new StatefulServiceContext()) simply won’t compile, neither you can easily inherit one or another, e.g. class MockedStatelessServiceContext : StatelessServiceContext.
  • Both StatelessService and StatefulService require the exact type of their respective context type, i.e. public StatelessService(StatelessServiceContext context), what means you cannot mock their base class so Mock.Of() won’t satisfy service’s ctor and it will fail in runtime (or in test time if you have appropriate test, and you should!).

Would be a bleak picture which would bury the whole idea. But ServiceFabric.Mocks to the rescue! Thank to it we can easily mock both contexts:

[TestClass]
public class ContainerConfigTest
{
    [TestMethod]
    public void Verify_MyStatefulService_Container_Should_Not_Throw_Exception()
    {
        // Arrange
        var container = ContainerConfig.CreateContainer(MockStatefulServiceContextFactory.Default);

        // Act
        // Assert
        container.Verify(VerificationOption.VerifyAndDiagnose);
    }

    [TestMethod]
    public void Verify_MyStatelessService_Container_Should_Not_Throw_Exception()
    {
        // Arrange
        var container = ContainerConfig.CreateContainer(MockStatelessServiceContextFactory.Default);

        // Act
        // Assert
        container.Verify(VerificationOption.VerifyAndDiagnose);
    }
}

That’s it! Now both of your stateless and statefull services themselves and all their dependencies are recursively instantiated and controlled by the container, plus their registrations are tested.

This entry was posted in Programming and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.