Introducing the Unit Testing Context Pattern

Introducing the Unit Testing Context Pattern

Another pattern?

Well yes. I write unit and integration tests almost every day and along the way i learned all kinds of different tricks and gotchas on how to be more productive and how to write less fragile tests.

But one of the patterns that emerged i never saw in the code of other people so i decided to share it here since i find it very useful.

I call it Testing Context Pattern and – unlike it’s name – its very simple.

Idea is to create in your Test Fixture a private class called (you guessed it) TestContext and put all the mocks/instances needed for testing the current class and then create instance of that class we test by using those mocks and then also expose all of that as public fields of the TestContext.

That way we have all we need for testing in one place and we can start having fun!

So if we are testing class WebPageDownloader that needs two more entities to function (IUrlPermissioner and IUrlRetriever) then we create class TestContext like this:

        private class TestContext
        {
            public Mock<IUrlPermissioner> PermissionerMock;
            public Mock<IUrlRetriever> UrlRetrieverMock;
            public WebPageDownloader Downloader;
        }

Notice here that we expose the mocks of the dependencies on the context (I’m using Moq testing framework but you can choose any other you like) this is very important because later in our tests we can then give further setups/expectations to those mocks that are used inside test class.

Next we create a private method on test fixture that creates instance of context for us, initializes it with all the mocks needed for testing and the tested class instance itself and returns it (this is to avoid creating this in each test):

        private TestContext CreateContext()
        {
            var ctxt = new TestContext()
            {
                PermissionerMock = new Mock<IUrlPermissioner>(),
                UrlRetrieverMock = new Mock<IUrlRetriever>(),
            };

            ctxt.Downloader = new WebPageDownloader(ctxt.PermissionerMock.Object, ctxt.UrlRetrieverMock.Object);

            return ctxt;
        }

As you see i create all the mocks that our tested class needs, then i instantiate it by passing mocked instances into its constructor and then i save mocks and target class in the context for usage in further tests.

Testing Context in action

So now in each test i call CreateContext method to get fresh instance of TestContext and start testing my target class.
Good thing about this is that in the TestContext we have all the mocks of dependencies used to create the tested class, so we can still manipulate them, mock out some specific methods for each test, and also we can check later in the test if the mocks were used in proper way, check what methods the target class invoked on them etc.

Here is an example of test that checks if our class throws exception for URl that is not permitted by IUrlPermissioner:

        [Test]
        [ExpectedException(typeof(SecurityException))]
        public void Download_WhenNotPermitted_Throws()
        {
            var ctxt = CreateContext();

            var badUrl = "http://www.SomeBadUrl";

            // arrange
            ctxt.PermissionerMock.Setup(a => a.IsUrlAllowed(badUrl)).Returns(false);

            // act
            ctxt.Downloader.Download(badUrl);

            // assert we don't need to do since we have ExpectedException attribute
        }

As you can see in the test we just call the CreateContext method to get fresh context, then we use the mocks from the context to setup our expected calls and return values, and then we invoke actual method on the class we are testing and then we expect the exception (via ExpectedException attribute that we placed on the test method)

Here is little more complex scenario where we setup multiple mock interactions with our class and then expect return result to be correct:

        [Test]
        public void Download_WhenAllowed_ShouldReturnWebpageGotViaRetriever()
        {
            var ctxt = CreateContext();

            var OkUrl = "http://www.SomeOkUrl";
            var OkUrlContent = "Some Web Page";

            // arrange
            ctxt.PermissionerMock.Setup(a => a.IsUrlAllowed(OkUrl)).Returns(true);
            ctxt.UrlRetrieverMock.Setup(a => a.Retrieve(OkUrl)).Returns(OkUrlContent);

            // act
            var result = ctxt.Downloader.Download(OkUrl);

            // assert
            Assert.AreEqual(OkUrlContent, result);
        }

Another good thing here is that if you later refactor your target class and add/remove dependencies you can easily change TestContext and CreateContext method accordingly and none of your existing tests should fail to compile because of that, unlike the situation when you would do all this in each test.

As usually, you can download Visual Studio 2012 solution showing this in action if you are interested.

I hope this simple pattern can help someone in writing better tests.
If you have comments or if you are doing something similar in your tests leave a comment i would love to hear it.

1 thought on “Introducing the Unit Testing Context Pattern

Leave a Reply to Dr Herbie Cancel reply