Java Unit Testing
Avoid System.out methods (JUT-001)
System.out is never necessary in unit test. The unit test framework already provides sufficient output in case of failures, so there is no need to add more output.
// Bad
System.out.println("Converting Entity");
convert(xyz);
// Better
assertNotNull(convert(xyz));
similarly, there is no need to add a message to the assertion. The framework is sufficient most of the time as it will indicate what line in the code the assertion failed
// Bad
assertTrue("Convert entity failed", convert(xyz) != null);
// Better
assertNotNull(convert(xyz));
Avoid calling the fail method (JUT-002)
Calling fail() is rarely necessary, use an assertion instead
// Bad
if (xzy != 123) {
fail("xyz is not 123");
}
// Good
assertEquals(123, xzy);
In the example above, the framework will also print the actual value of xyz if it is not equals to 123.
Prefer assertEquals over assertTrue method (JUT-003)
// Bad
assertTrue(a.size() == 5);
// Good
assertEquals(5, a.size());
The reason the second implementation is better is that in case of failure, the message will be more explicit, saying something like “Expected 5 but was 4” (so you know the list is empty) whereas with the assertTrue, the message will be “Expected true but was false” which is not very helpful.
Avoid catching exception (JUT-004)
Unit tests should not catch exception. In case of a failure, the test framework will actually take care of printing the stack trace, so no need to re-implement it everywhere.
// Wrong
public void testErrors() {
try {
// The test
} catch (SomeException e) {
e.printStackTrace();
assertFalse("Should not error", true);
}
}
// Correct
public void testErrors() throws Exception {
// The test
}
Avoid extra null pointer check (JUT-005)
It is not necessary to assert for not null before accessing some property on an object.
// Bad
assertNotNull(outputData);
assertNotNull(outputData.get(CommonUIDataTypes.HOSTNAME_DATA));
// Good
assertNotNull(outputData.get(CommonUIDataTypes.HOSTNAME_DATA));
In the second case, even if outputData is null, it will throw a NullPointerException which the testing framework (junit/testng) will catch and the test will fail.
Avoid printStackTrace (JUT-006)
Same as System.out, no need to print the stack trace. Let the framework handle it for you.
Avoid using environment variables (JUT-007)
Environment variables should not be required to run unit tests. A simple “run” from eclipse should just work without relying on the configuration of the environment (e.g. additional software installed, specific files stored in a location).
Avoid hard coded file system path (JUT-008)
Some tests might require to load or write files. The path of such file should not be absolute path that are depending on the environment (e.g. no "C:\"). Instead, use relative path, temp file or folder (e.g. FileUtils#createTempDirectory method)