Site Loading

Almost anyone working in development these days will say that unit tests are an integral part of any application development.  I think  the reality of a lot of application development does not have unit testing.  It would be interesting to find out how many projects have unit testing and what the test coverage is.

The point of this post is not to complain about the lack of unit testing but to look at the process of creating quality unit test for a project.

The first thing to note is that what most people think is a unit test, is actually an integration test.  The best way to explain it would be give the definition of both a unit test and an integration test.

A unit test: is a method that calls another method and tests the outcome of the method against a set of assumptions.

An integration test: is a test that tests a set of dependant modules.

It becomes obvious when you look at the definitions that when people try and write unit tests they inadvertently create integration tests.

The obvious benefit of unit testing is a reduction of bugs.  You might say that it would be obvious but it should be mentioned since it can show bugs with the push of a button or a build environment.  This allows teams to make sure that enhancements or changes will not break existing functionality.

It also makes code easier to understand.  The tests themselves give the programmers the understanding of what the methods should be doing.

There are a number of good guidelines to writing unit tests on the internet.  Here is some of the wisdom of the internet:

Make sure that the test is not inadvertently testing more than one method.  This includes loading data from the database, using the file system in any way.

Make sure that the tests can be run easily without any config file.

A clever way of making sure you are creating unit tests and not integration tests can be achieved by using Stubs.

Stubs are a replacement for a dependency that the method that needs to run.  To be able to use stubs, the code must be written in such a way that different providers can be used as dependencies.  By this i mean if the code was checking a folder for a file, the dependency might be replaced by a stub that provides the code with a way of interacting with a fake file system so that the unit test remains a unit test.

The last thing I would like to mention is Test driven design.  Test driven design works by writing a test to solve a particular problem.  The developer would write the test case that would fail since there is no code, then write the code to make the test pass.  By writing tests first the project should have a high code coverage.  Not to mention the fact that by writing the test, the developer focuses on the task at hand which is only to make the test pass.

This is by no means a comprehensive article on unit testing but I hope that it helps people on their way to 100% test coverage.

kick it on DotNetKicks.com

Close