Writing unit tests can be challenging, but there is one thing that can get you on the right track — the test name.

If you manage to give your test a good name — you will write a good test.

Unfortunately in some ( read: many) unit testing frameworks the test name must be a valid method name — because those “unit tests” actually function inside a class and so they look something like this:

Java

public class CalculatorTests {
@Test
void add_passTwoPositiveNumbers_returnSum() {
Calculator calculator = new Calculator();
int result = calculator.add(2, 3);
assertEquals(5, result)
}
}

Test Names

In my tests, I’ve been using the naming scheme created by Roy Osherove. It forces you to think about the test before you write it and keep you from writing horrible unit tests.

The test names are built from three parts:

  1. The **method **running the test — this is the play button that would be used to execute the “experiment”
  2. The **scenario **we test — what is the system state before running the method, what input is used during the test — in other words, “what makes this test different from any other test ever written”.
  3. The expected result — what we expect to happen when we run the method (1) with the specific state (2).

The good thing about using structured test names is that when a test fails we understand immediately what went wrong. Test names tell use what we’re testing and what we expect to happen and together with the error message (from an assertion) we should quickly understand what went wrong, fix it, and have the code back to running smoothly in no time.

#tutorial #performance #junit #problems #display name #test names

Better Tests Names Using JUnit's Display Name Generators
1.65 GEEK