DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Selecting the Right Automated Tests
  • Supercharging Productivity in Microservice Development With AI Tools
  • Mastering Node.js: The Ultimate Guide
  • Improving Customer-Facing App Quality Using Tricentis Testim

Trending

  • REST vs. Message Brokers: Choosing the Right Communication
  • Getting Started With Prometheus Workshop: Instrumenting Applications
  • Revolutionizing Software Testing
  • Agile Metrics and KPIs in Action
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Introducing the Unit Testing Context Pattern

Introducing the Unit Testing Context Pattern

Slobodan Pavkov user avatar by
Slobodan Pavkov
·
Jan. 17, 14 · Interview
Like (0)
Save
Tweet
Share
13.75K Views

Join the DZone community and get the full member experience.

Join For Free

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 ContextPattern 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.

unit test

Published at DZone with permission of Slobodan Pavkov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Selecting the Right Automated Tests
  • Supercharging Productivity in Microservice Development With AI Tools
  • Mastering Node.js: The Ultimate Guide
  • Improving Customer-Facing App Quality Using Tricentis Testim

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: