This is a series of blog posts:
- Part 1: Stateful service
- Part 2: Stateless service
- Part 3: Unit testing
Unit testing of the final construct we’ve got in previous two parts would be challenging due to a number of reasons:
- Both
StatelessServiceContext
andStatefulServiceContext
aresealed
, 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
andStatefulService
require the exact type of their respective context type, i.e.public StatelessService(StatelessServiceContext context)
, what means you cannot mock their base class soMock.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.