Javadoc in JUnit test classes?
I use Javadoc in my testing a lot. But it only gets really useful when you add your own tag to your javadoc.
The main objective here is to make the test understandable for other developers contributing to your project. And for that we don't even need to generate the actual javadoc.
/**
* Create a valid account.
* @result Account will be persisted without any errors,
* and Account.getId() will no longer be <code>null</code>
*/
@Test
public void createValidAccount() {
accountService.create(account);
assertNotNull(account.getId());
}
Next we'll need to notify our Javadoc plugin in maven that we added a new tag.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8</version>
<configuration>
<tags>
<tag>
<name>result</name>
<placement>a</placement>
<head>Test assertion :</head>
</tag>
</tags>
</configuration>
</plugin>
</plugins>
</build>
And now all that is left to do is call our maven plugin.
javadoc:test-javadoc (or javadoc:test-aggregate for multi-module projects)
This is a fairly easy example, but when running more complex tests, it is impossible to describe the tests by simply using a self-descriptive method name.
I personally use javadoc comments sparingly as I find they increase the on-screen clutter. If I can name a class, function or variable in a more self-descriptive way then I will in preference to a comment. An excellent book to read on this topic is Clean Code by Robert C. Martin (a.k.a Uncle Bob).
My personal preference is to make both the class and methods self descriptive i.e.
class ANewEventManager {
@Test
public void shouldAllowClassesToSubscribeToEvents() {
/* Test logic here */
}
}
One advantage of this approach is that it is easy to see in the junit output what is failing before browsing the code.