DevOps Zone is brought to you in partnership with:

Software developer and solutions designer of large distributed systems and frameworks. Luis is a DZone MVB and is not an employee of DZone and has posted 7 posts at DZone. You can read more from them at their website. View Full User Profile

Unit Testing 101: Creating Flexible Test Code

02.14.2014
| 7073 views |
  • submit to reddit

Introduction

When going for test-driven development, we all know that the unit test code becomes critical part of the code base. Additional to this, it even ends up representing a bigger percentage of the overall code base than the actual business code. Is because of this that it is really important to have a solid unit test source code structure; flexible, intuitive and maintainable enough so that when the amount of unit tests grow, it does not become an uncontrollable mess.

Always remember: unit testing is not done because is a nice to have or because test-driven development is trendy and cool; it is done because is needed and is critical in order to ease the development cycle and ensure product quality.

Academic v.s. Real Life

Most articles we follow on the internet on how to build unit tests often use small or reduced scopes in order to keep the concepts easy to digest and understand. For example, they demostrate how to create one or two unit tests to test a simple application feature, like a calculator capability to add two numbers. The problem raises when we get the next day in our computers at work and try to apply our newly acquired knowledge to a more realistic scope: We realize that, in real life, we would have thousands of units tests for a thousand features and not one or two like in the articles we learned from.

So, the question is: What do we do when we go beyond examples and get into testing a real-life application?

The Scenario

Before we can continue, lets use the scenario we mentioned previously. Lets assume we are working in an online shopping application. We are about to create a REST service that allows web clients to handle orders from customers. That service will eventually feature several methods to place new orders, cancel orders, track orders, etc. We'll need to create a bunch of unit tests for that service and all of its methods.

A Flexible Structure

Now, we have a scenario. Assuming the orders service eventually will feature a bunch of methods, unit tests must cover all of these methods and all of its possible success and failure scenarios. This could result in a couple dozen test methods in no time. What do we do? Do we go down the usual path and put all of these test methods in a single test class since it is testing a single component?

Short answer: No. You don't do that.

We are starting to see that grouping tests per-component is not enough in order to keep test classes small, so we need to break down grouping one more level. In the case of the orders service, our next grouping level would be per-component feature. We have now two levels of unit test grouping:

  • Component tests: Top-level group of unit test suites that target a single component. In this case, the orders service.
  • Component feature tests: Sub-level that group the test suites that target a single component feature. In this case, the orders service method for placing orders.

Now, how does this look in code?

The Unit Test Code 

In C#, we can create a single class composed of multiple source files. This is done by using partial classes. So, we will start by defining a new partial class that will represent a part of the component test suite class.

[TestFixture]
partial class OnOrdersService 
{
    // More code here on a second...
}

The component test suite class uses the following naming convention:

public [partial] class On[ComponentName] { }

So, when reading the name we have a clear idea of what's the target component to be tested by the suite. Right after the feature test suite class declaration, we start defining the component feature test suite class. This will be a class nested inside the feature test suite class.

[TestFixture]
partial class OnOrdersService
{
    [TestFixture]
    public class WhenPlacingOrders
    {
        // Component feature test methods to be added here soon...
    }
}

The component feature test suite class uses the following naming convention:

public class When[ActionPerformed][FeatureName] {}

Of course, the next thing to do is add some test methods. Lets expand our example: 

[TestFixture]
partial class OnOrdersService
{
    [TestFixture]
    public class WhenPlacingOrders
    {
        [Test]
        public void ShouldReturnOrderIdOnValidOrderPlaced()
        {
            // Test code for a success scenario...
        }
        
        [Test]
        public void ThrowErrorOnInvalidOrderPlaced()
        {
            // Test code for a failure scenario...
        }
    }
}

The success scenario test methods use the following convention:

public void Should[ExpectedOutcome]On[ScenarioCondition]();

.. and failure scenario use:

public void Should[ExpectedFailure]On[FailureConditions]();

Before you stop reading and yell in anger on those funky class names, lets try to read textually down our hierarchy:

On orders service... when placing orders... should return order ID on valid order placed.

So, by now you should be getting a clearer picture on what we are trying to achieve here. By manipulating class structures (partial and nested classes) we can organize our tests by component and then by component feature while keeping an intuitive and readable structure. This will allow us to keep test classes small and easy maintainable. If you don't trust me with the previous example, this is how the Visual Studio test runner looks when using our handy class structure.

    Now, lets say that we would like to add tests to cover the service method that cancels orders. In this case we would create a new partial class using the same OnOrdersService class name. We then create a new nested class called WhenCancellingOrders.

Now we have a component test suite class split in two files. Each file will contain a single component feature test suite. 

I think is time we discuss what naming convention these files should follow. Our test runner looks pretty now, but our file structure, which has nothing to do with the runner; has to look pretty as well. We will use the following convention:

On[ComponentName]When[ActionPerformed][FeatureName].cs

For example:

OnOrdersServiceWhenPlacingOrders.cs
OnOrdersServiceWhenCancellingOrders.cs

    There you go. Now it looks good enough. We can go further and play a little with the namespaces, but that is out of the scope of this article.

Conclusion

That would be it. We now have a consistent test code structure that can grow gradually as requirements and features are added. In future articles we will go through unit test method structuring and test contexts in order to delegate test contest setup code like mocking objects and such.

Published at DZone with permission of Luis Aguilar, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)