Use a Before Method in Your Tests

When writing unit tests using the JUnit like frameworks, the mantra is to avoid any work in the class and prefer putting initialisation logic in a dedicated before method.

Imagine you’re testing JSON manipulation and you have sample fixture data to work on.

public class WhyUseBeforeTest {
  static Json.Array fixture = (Json.Array) Json.fromString("[5,6]");
  @Test
  public void example() {
    assertEquals(2, fixture.size());
  }
}

(The library used here is the JsonMarshaller and all values are immutable.)

Everything works fine! So why go through the trouble of the before method?

A week later, a team mate wants to make the fixture a bit more complicated.

public class WhyUseBeforeTest {
  static Json.Array fixture = (Json.Array) Json.fromString("[5,6,7,]");
  @Test
  public void example() {
    assertEquals(2, fixture.size());
  }
}

He launches all the tests and nothing runs any more!

It turns out, the JSON expression is incorrect and has an extra comma "[5,6,7,]" which as a result causes an exception when loading the class which in turns breaks runners.

If instead we had used the before method

public class WhyUseBeforeTest {
  Json.Array fixture;
  @Before
  public void before() {
    fixture = (Json.Array) Json.fromString("[5,6,7,]");
  }
  @Test
  public void example() {
    assertEquals(2, fixture.size());
  }
}

we would have had a clear failure and big error message.

There are two other reasons why you would want to use a before method

  • Isolation By creating the data fresh each time you guaranty that there is no shared state.
  • Load Time Since static initialisation code runs when classes are loaded you pay the initialisation cost even if you do not run the specific test.

Have fun our your TDD journey and think of your peers whenever you are writing code. Best practices ensure consistency and are usually motivated by many more concerns that one can think of at once in the middle of feature development.