Tag: test driven development

It ain’t a Unit Test just because you used xUnit

Posted by on December 2, 2008

Test Driven Development (TDD) is great. When I started unit testing and TDD with JUnit about six years ago, it was a relatively new concept. I was impressed by the way it helped development, and led to developing better code. However, it’s only now that I realize how little I knew about unit testing back then.

I can remember an XP project where we developed an enterprise application which had two layers of session beans, and entity beans that got persisted in an Oracle database. We used to have unit tests (that’s what we called them) testing all layers, accessing the session beans and propagating all the way down to the entity beans and to the database. As a result of testing all layers, running the whole suite of tests took us about one and a half hours. We were not convinced that our so called unit tests added any value to the project as it took us so much time to use them properly. So we ended up running only groups of tests together, and not the whole suite.

Recently I stumbled upon an article by Michael Feathers that literally describes the same issue we faced. He lays down the following rules:

A test is not a unit test if:
1.It talks to the database
2.It communicates across the network
3.It touches the file system
4.It can’t run at the same time as any of your other unit tests
5.You have to do special things to your environment (such as editing config files) to run it.

The main takeway from this is that the purpose of a unit test is to test the functionality of a particular unit of code. It need not test all the layers of functionality upon which the class being tested depends (e.g. entity beans, databases etc.). In our case, we could have used mock objects to separate the business logic from the underlying persistence layers. This should have allowed us to simply test the business logic of our classes using unit tests without effectively writing comprehensive but bulky functional tests. We could have defined our classes with dependency injection in mind. Dependency injection is the practice of writing testable code by separating code for object creation and business logic, and passing all dependent objects through the constructors of objects.

The Google tech-talk below provides a great explanation of this concept:

So, just because you use an xUnit framework and write automated tests for your classes, they don’t necessarily become unit tests.
Bookmark and Share