Writing unit tests using BDD style

Well written tests could be seen as part of good documentation, but rather often it is of no help at all. Take for example this test

@Test
public void testOne() {
String a = "Kalle";
int b = someService.someMethod(a);
assert(b, 2);
}

Seing this code or the test report does not give us a clue what the test does or what the code we are testing should do. There are better ways of doing this and I tend to favor unit tests using the Behavior-driven development (BDD) style to structure the unit test.
First of all it is important to give a (as close to) self explaining name of the test method of what the test is testing and the expected result. Don’t forget to remove the “test” in the methods name since it is obvious this is a test. The method is annotated, right? Secondly it is possible to use the given-when-then BDD styel in a unit test as well.

@Test
public void whenKalleIsUsedAsUserNameWhensomeMethodIsCalledThereShouldBeTwoOfThem() {
// Given a first name "Kalle"
String a = "Kalle";
// When service is requested for the number users with Kalle as first name
int b = someService.someMethod(a);
// Then there should be two of them
assert(b, 2);
}

This might a stupid example, but using this structure it makes it more obvious to the reader what the test is about. Using a proper method name makes it easier to spot what went wrong reading the error report of your build.