Sub topic 7
Structuring and Naming Tests
A test that passes today will fail some day, maybe months from now. When that happens, someone has to read it and work out what went wrong. That person might be a teammate, or it might be you after you have forgotten the details. This chapter shows how to lay out a test and name it so the reader understands it quickly.
You will learn three things:
- The Arrange-Act-Assert pattern, a simple layout for the inside of a test method.
- How to choose test names that say what behavior is being checked.
- How to use
@DisplayNameto show readable names in test reports.
Why Structure Matters
A test report is the list of passed and failed tests that your IDE or build tool shows after a run. Often the name of a failed test is the first thing you see. If the name is test1, it tells you nothing. If the name is "divide by zero throws an error", you already know which behavior broke before you open the file.
The inside of the test matters too. A messy test mixes setup, actions, and checks together. Then the reader has to untangle it before fixing anything. A clear structure saves that time.
The Arrange-Act-Assert Pattern
Arrange-Act-Assert (often shortened to AAA) is a way to split every test method into three parts:
- Arrange: create the objects and data the test needs.
- Act: call the one method you are testing.
- Assert: check that the result is what you expected.
Here is the Calculator class used in earlier chapters. It is the code under test, meaning the production code that the tests check.
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("divisor must not be zero");
}
return a / b;
}
}This test follows AAA. The comments mark each part.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class CalculatorAaaTest {
@Test
void addReturnsSum() {
// Arrange
Calculator calculator = new Calculator();
// Act
int result = calculator.add(2, 3);
// Assert
assertEquals(5, result);
}
}A blank line between the parts is usually enough once you are used to the pattern. The comments are optional, but they help while you are learning.
When Act and Assert Merge
Sometimes the act and the assert happen in a single line. Testing an exception is the usual case, because assertThrows both calls the method and checks the outcome:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class CalculatorDivideTest {
@Test
void divideByZeroThrows() {
// Arrange
Calculator calculator = new Calculator();
// Act and Assert
IllegalArgumentException ex = assertThrows(
IllegalArgumentException.class,
() -> calculator.divide(10, 0));
assertEquals("divisor must not be zero", ex.getMessage());
}
}That is fine. The goal is a clear order, and you don't need to force three separate blocks.
One Behavior per Test
A behavior is one thing the code should do in one situation, such as "adding two positive numbers gives their sum". A good test checks one behavior.
Compare these two approaches:
| Approach | What happens when something breaks |
|---|---|
| One big test checks `add`, `divide`, and divide by zero | The first failed assertion stops the test. You don't learn whether the other parts work. |
| Three small tests, one per behavior | Each failure appears on its own, with its own name in the report. |
A test can still contain more than one assertion, as long as all of them describe the same behavior. Checking both the type of an exception and its message is one behavior. Checking addition and division in the same test is two behaviors.
Naming Test Classes
Test classes follow simple conventions that build tools and IDEs expect:
- Name the test class after the class it tests, plus
Test.Calculatoris tested byCalculatorTest. - Put production code in
src/main/javaand tests insrc/test/java. - Use the same package for the test as for the class under test. A package is Java's way of grouping classes into folders. Using the same package lets the test reach methods that are not
public.
src/
main/java/com/example/Calculator.java
test/java/com/example/CalculatorTest.javaBy default, Maven's Surefire plugin runs classes whose names end in Test, Tests, or TestCase, or start with Test. If you name a class CalculatorChecks, Maven will quietly skip it.
Naming Test Methods
A good method name tells the reader what is tested, under what condition, and what should happen. Teams use several styles. Pick one and use it everywhere in a project.
| Style | Example |
|---|---|
| Plain camelCase sentence | `addReturnsSum` |
| method_condition_result | `divide_byZero_throwsException` |
| should style | `shouldThrowWhenDividingByZero` |
| given/when/then | `givenZeroDivisor_whenDivide_thenThrows` |
Avoid names like these:
test1,testAdd2: they say nothing about the expected result.testDivide: it names the method but not the behavior. Divide has several behaviors.- Very long names that repeat the class name, such as
calculatorAddMethodShouldAddTwoNumbersTogetherCorrectly.
Readable Names with @DisplayName
Java method names cannot contain spaces. The @DisplayName annotation lets you give a test a free-form name for reports. The text can contain spaces, punctuation, and even emoji.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@DisplayName("Calculator")
class CalculatorTest {
@Test
@DisplayName("add returns the sum of two numbers")
void addReturnsSum() {
Calculator calculator = new Calculator();
int result = calculator.add(2, 3);
assertEquals(5, result);
}
@Test
@DisplayName("divide by zero throws IllegalArgumentException")
void divideByZeroThrows() {
Calculator calculator = new Calculator();
assertThrows(IllegalArgumentException.class,
() -> calculator.divide(10, 0));
}
}In the IDE's test window you will now see:
Calculator
✔ add returns the sum of two numbers
✔ divide by zero throws IllegalArgumentExceptionThe method name still exists and still has to be valid Java. @DisplayName only changes what the report shows.
Generating Display Names Automatically
Writing @DisplayName on every method takes effort. @DisplayNameGeneration tells JUnit to build display names from method names. The built-in ReplaceUnderscores generator turns underscores into spaces:
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.DisplayNameGeneration;
import org.junit.jupiter.api.DisplayNameGenerator;
import org.junit.jupiter.api.Test;
@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
class CalculatorNamingTest {
@Test
void add_returns_the_sum_of_two_numbers() {
Calculator calculator = new Calculator();
assertEquals(5, calculator.add(2, 3));
}
}The report shows "add returns the sum of two numbers". An explicit @DisplayName on a method overrides the generated name.
Edge Cases and Common Mistakes
- Hidden arrange steps. If the setup is long, a reader may miss the important input. Keep the values that matter to this test inside the test, where they can be seen.
- Several acts. Calling the method under test twice, then asserting, makes it unclear which call failed. Use one act per test.
- Logic in tests.
ifstatements and loops inside a test can hide bugs in the test itself. Keep tests straight-line code. - Names that lie. If you change what a test checks, rename it. An outdated name misleads whoever reads the report next.
- Duplicate display names. JUnit allows two tests with the same
@DisplayName, but the report becomes confusing. Keep each one unique within a class.
Exercise
Rewrite the name testDivide2 for a test that checks that dividing 10 by 2 returns 5, using the methodconditionresult style.
Show answer
A good name is divide_evenNumbers_returnsQuotient (or similar, such as divide_tenByTwo_returnsFive). It names the method, the condition, and the expected result.
Exercise
A test creates a Calculator, calls add(2, 3), asserts the result is 5, then calls divide(10, 0) and asserts it throws. What is wrong with its structure, and how would you fix it?
Show answer
It checks two behaviors and has two Act steps, so a failure in the first assertion hides the result of the second. Split it into two tests, such as addReturnsSum and divideByZeroThrows, each with its own Arrange, Act, and Assert.
Exercise
You add @DisplayName("adds numbers") to a method named test1. Why should you still rename the method?
Show answer
Some tools and CI reports show the method name instead of the display name, so test1 would still appear and tell the reader nothing. The method name should describe the behavior on its own.