Skip to main content

Avoid multiple acts

When writing unit tests using the AAA pattern, try to include only one act per test case. If you need to call the Act behavior with different parameters then consider using parametrized tests.

Frameworks like JUnit offer the support for creating parametrized unit tests Using this pattern can help developers to their focus on just one single case at a time. When the test fails it becomes easy to determine which "Act" is failing.

Example

Consider the static method NumbersUtility.isOdd() that returns true if the param number is odd.

@Test
void isOdd_ShouldReturnTrueForOddNumbers() {
assertTrue(NumbersUtility.isOdd(1));
assertTrue(NumbersUtility.isOdd(3));
assertTrue(NumbersUtility.isOdd(5));
assertTrue(NumbersUtility.isOdd(-3));
assertTrue(NumbersUtility.isOdd(Integer.MAX_VALUE));
}

Improved example

Using Junit support for parametrized tests. If the test fails, the framework will provide is with the parameter that did not satisfy the assertion.

@ParameterizedTest
@ValueSource(ints = {1, 3, 5, -3, 15, Integer.MAX_VALUE})
void isOdd_ShouldReturnTrueForOddNumbers(int number) {
assertTrue(NumbersUtility.isOdd(number));
}