Unit Testing Succinctly: Advanced Unit Testing

This is an extract from the Unit Testing Succinctly eBook, by Marc Clifton, kindly provided by Syncfusion.

In this article, we're going to begin talking about a few of the advanced topics that come with unit testing. This includes things such as cyclometric complexity, methods, fields, and reflection.

Cyclometric Complexity

Cyclometric complexity is a measure of the number of independent paths through your code. Code coverage testing is intended to ensure that your tests execute all possible code paths. Code coverage testing is available in Visual Studio’s Test, Premium, and Ultimate versions. Code coverage is not part of NUnit. A third-party solution, NCover, is also available.

To illustrate this issue, consider this code, which parses command line parameters:

and a couple of simple tests (note that these tests omit the code paths that result in exceptions being thrown):

Now let’s look at what a code coverage test might look like, first by writing a poor man’s code coverage helper:

We’ll also need a simple extension method; you’ll see why in a minute:

Now we can add coverage set-points in our code, which will be compiled into the application when it is compiled in DEBUG mode (the bold red lines where added):

And now we can write the following test fixture:

Note how we are now ignoring the actual results, but are ensuring that the desired code blocks are being executed.

White Box Testing: Inspecting Protected and Private Fields and Methods

Arguably, a unit test should only concern itself with public fields and methods. The counterargument for this is that in order to test the entire implementation, access to protected or private fields, to assert their state, and the ability to unit test protected or private methods is required. Considering that it is probably not desirable to expose most low-level computations, and those are exactly the methods one wants to test, it is most likely that testing at least protected or private methods is necessary. There are several options available.

Exposing Methods and Fields in Test Mode

This example illustrates the concept:

While this is doable, it produces ugly source code and runs the serious risk that someone might actually call the method with the symbol TEST defined, only to discover that his or her code breaks in a production build where the TEST symbol is undefined.

Deriving a Test Class

As an alternative, if the methods are protected, consider deriving a test class:

This allows you to instantiate the derived testing class and access a protected method via a publicly exposed method in the subclass.

Reflection

Lastly, one can use reflection for private methods or sealed classes. The following illustrates a private method and executing that method via reflection in a test:

Tags:

Comments

Related Articles