Test Code Comments

Once upon a time I strongly believed that comments in test classes are obsolete. I believed, that they can always be replaced by:

  • better naming of test methods and variables,
  • splitting test methods into smaller and more focused.

I still believe that good naming and focused test methods are essential. However, I do not claim anymore that comments are not required in the test code. My test code is almost free of comments but there are at least few places that I use them.

So, keeping in mind that in general there is no need to put comments in test code lets discuss few situations when adding them seems legit.

Bugs

When adding a test because of a reported bug, I usually add a ticket number so one can find the issue on bug tracker, and (optionally) write a short explanation of what the problem was, e.g.:
"#12345 NPE when user name not provided"
This additional comment is not always needed, since the method name usually tells the story good enough.

Date Sets

Sometime, I also add a comment on the reasons for selecting a particular set of test data. This often has something to do with business requirements, and cannot be read from the code.

For example, when testing some time-dependent method it might be not obvious why results for Sydney and Lisboa are tested. A short comment like "need to verify results for different hemispheres" makes it obvious.

Want to learn more about unit tests? See my book
"Practical Unit Testing"

Surprising Stuff

It also happens that some tests of legacy code which use non-standard techniques require a comment. By "non-standard" I mean rarely used tricks, like subclassing of the SUT, using the Mockito's spy() method, or using reflection for setting/reading some of the SUT's properties.

Integration and End-to-End Tests

The situation is different when it comes to higher level tests, especially end-to-end tests.

These tests tend to be quite long, and even though I try to write them so their business purpose (scenario) is clear, this is not always simple to achieve. So I believe commenting on what is happening there is valuable.

And What About You?

I would be very happy to learn in what situations do you add comments to your test classes.

Ticket numbers look better in

Ticket numbers look better in every commit message :) Intellij generates annotations quite fast and weird numbers just don't clutter the code

not sure

Sure you should put ticket number in commit!

But sometimes commits contains few classes so it is harder to put very detailed description there. This is why I think it is a good idea to put an additional comment right next to the test method. Besides, it is much more convenient for the reader to have the comment in the code instead of browsing git/svn history.

 
 
 
This used to be my blog. I moved to http://tomek.kaczanowscy.pl long time ago.

 
 
 

Please comment using