The ultimate test template

Recommended reading before you read this article: Mockito basics, Fest assertions.

When doing OOP we create objects. While doing TDD we should focus on relationships between those objects. That being said, one of the main principles that we should focus on is “Tell Don’t Ask”. We tell object “do this thing” and expect a certain result. This leads us to the “ultimate test template”, a test should have 3 parts: inputs for the tested object, call on the object and then asserting for the expected results, for example:

This is a very basic example just to illustrate the 3 parts of the test. The input is that the User object was supplied with an observer. The output is that if user changed password is that the observer was notified. (This example uses Mockito mocks to create a mock object and then verify if a method was called on it).

You might notice the comments //given //when // then. At the beginning I added them each time I was staring a new test, but after a while I realised that this just adds noise. When you know that each test will have those 3 parts I would skip the comments.

Sometimes the first or third parts may be skipped of course. For example we may skip the first part (the givens are in the same line as the call for readibility):

Or we can skip the first and last part. The third part is moved to the annotation parameters:

InteliJ IDEA users

You might add a live template to your IDE. Go to File->Settings->Live Templates.
Add the listing below to “plain” category. The abbreviation should be “test”.
Do not forget to check “Context -> Java Code”.

Now when you type “test” and pres TAB in a java file the test template will appear.