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)) {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.
list.remove(s);
}
else {
fail("Object " + s + " not in list!");
}
}
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).
Resources
Other publications about TDD:
- Scope of Unit Tests
- A Series on Test Driven Develolpment
- Test-Driven Development Is Not About Testing
- TDD for Beginners
- TDD is like teenager sex
- It's time to drop the 'T' from TDD
- Agitator and TDD
- Introduction to Test Driven Development (book excerpt)
- Getting Started (book excerpt)
- Unit Testing: The Foundation of Test-Driven Development (book excerpt)
- TDD and Genetic Programming
- How To Simulate Key Events In Swing JUnit Tests
No comments:
Post a Comment