Clean test AAA principle

The basic structure of a AAA (arrange-act-assert) test is:

  1. prepare the system-under-test for the test (the arrange step)
  2. exercise the system-under-test, which causes side-effects that are observable (the act step)
  3. verify that the side-effects match our expectations (the assert step)

Clean code principles dictate that methods be kept short. So how long is the perfect test if we apply clean code principles to testing? 3 lines long, or not much longer than that. That gives you one line per step, and allows you to keep everything in your head:

public void testAdder() {
    Calculator calc = new Calculator();
    int sum = calc.add(1, 1);
    assertThat(sum, is(2));

Where do you see such tests? Typically in unit tests resulting from TDD, where the scope of the test is very narrow. If your system-under-test is very cohesive and self-contained (as in the single-class calculator above), that’s fine. We should all be so lucky.

Next time, I’ll write about what happens when you have lots of simple tests. Stay tuned.