Test-Driven Development: Useful Techniques, Resources

Test-Driven Development (TDD) is subject of many publications. I feel that it never was seen as a hype. From my point of view, it is a really useful concept helping great in reducing errors. That seems proven, IMO. I used TDD in several projects, currently with JGAP and with a software package based on JRefactory.

I found out that many test cases rely on the same testing techniques, such as:

Type Cast
When testing if the return value of a method call conforms with a certain type, you could write:

   assertTrue("My String",vector.get(0));

Better would be:

   assertTrue("My String",(String)vector.get(0)); 

The latter ensures that we really get a String type back. The former could also be tue if the toString() method of the type returned is accordingly.
You could also use Type Case if you only wanted to ensure that an element at a given index in the list is not null and conforms to a special type.

Elements in unordered collection
If the result of a method under test is an unorded List or a Map, then it should nevertheless be tested whether obligatory elements exist in the collection and others do not. We can easily accomplish this by firstly building up an internal Map (e.g. java.util.HashMap) by putting in all elements that are expected to be returned by the method unter test.
After that we perform the method call. Then, we iterate over the returned list and call a helper method such as

   assertInList(final Map list, String s); 

This method could read like:
public void assertInList(final Map list, String s) {

  if (list.containsKey(s)) {
else {
fail("Object " + s + " not in list!");
Of course, you could extend this helper method for handling types delivered in the java.lang package. Sometimes a developer states java.lang.Comparable and sometimes he omits the package. By extending method assertInList to check for a string concatenated by java.lang and the string originally searched, we could make these instances equal.

Don't forget to write

     assertEquals(0, list.size());
after testing against the obligatory elements to ensure no other (unwanted) element is in the return list under test.

Molecular tests
It is not forbidden to include multiple asserts within one testcase. The advantage of only one assertion (or more generally: check) in a test case is that one could immediately see the point of failure. But with my IDE I could easily figure out the assertion faiiling just one mouse click later. Multipel assertions in one test case help validate more than one thing without the need of constructing again and again the input configuration (instantiatng objects, setting parameters).

Other publications about TDD:

No comments: