Naming and organising tests
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)When 200 ShopLite tests run, a report that says "test1 failed" helps nobody. Names and structure decide whether a red test tells you the bug before you open any file.
Naming styles: method_condition_result and should sentences
method_condition_result is a test naming style that names the method under test, the condition and the expected result, separated by underscores, like add_zeroQuantity_throwsIllegalArgumentException.
A test name should state the behaviour: the situation and the expected outcome. Pick one style per project and stay with it.
// method_condition_result@Test void add_zeroQuantity_throwsIllegalArgumentException() { ... }@Test void total_emptyCart_isZero() { ... }
// sentences@Test void addingAZeroQuantityIsRejected() { ... }@Test void shouldTotalZeroForAnEmptyCart() { ... }
// avoid@Test void test1() { ... }@Test void testAdd() { ... }The sentence style reads as plain English: addingAZeroQuantityIsRejected or shouldTotalZeroForAnEmptyCart. Avoid names like test1, testAdd or cartWorks: they say nothing when they fail.
Predict the output
Pick the best test name
Read the test body, then pick the name that explains a failure.
Round 1 of 2
Which name fits this test best?
@DisplayName and the display name generator
@DisplayName gives a test class or method a free-text name, with spaces and punctuation, for reports and IDEs. It does not change the method name, only what is shown.
The same tests can show readable names in a report. Compare an explicit @DisplayName with a generated name.
Example 1 · @DisplayName and ReplaceUnderscores in the report
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.math.BigDecimal;
import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.DisplayNameGeneration;import org.junit.jupiter.api.DisplayNameGenerator;import org.junit.jupiter.api.Test;
@DisplayName("Cart quantities")@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)class CartQuantityNamesTest {
@Test void a_zero_quantity_is_rejected() { assertThatThrownBy(() -> new Cart().add("NB-A5", new BigDecimal("60.00"), 0)) .hasMessage("Quantity must be at least 1"); }
@Test void adding_the_same_sku_again_adds_to_its_quantity() { Cart cart = new Cart(); cart.add("NB-A5", new BigDecimal("60.00"), 1);
cart.add("NB-A5", new BigDecimal("60.00"), 2);
assertThat(cart.itemCount()).isEqualTo(3); }
@Test @DisplayName("1 is the smallest quantity accepted") void smallestQuantity() { Cart cart = new Cart();
cart.add("NB-A5", new BigDecimal("60.00"), 1);
assertThat(cart.itemCount()).isEqualTo(1); }}Cart quantities a zero quantity is rejected adding the same sku again adds to its quantity 1 is the smallest quantity accepted
What this code does
- The class's
@DisplayNamereplacesCartQuantityNamesTestin the report, and the generator turns each underscore name into a sentence. This is the tree an IDE or a CI test report shows. - An explicit
@DisplayNameon a method wins over the generator, as forsmallestQuantity. Surefire's console summary still uses class names; display names show up in IDEs and in the XML reports.
A display name generator builds names for a whole class. @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) turns a_zero_quantity_is_rejected into "a zero quantity is rejected", so you get readable reports without writing every name twice.
@Nested classes grouped by scenario
@Nested marks a non-static inner class of a test class as a group of tests for one scenario, such as "when empty". It has its own @BeforeEach that builds the scenario on top of the outer class's set-up.
A cart behaves differently when it is empty and when it holds notebooks. Group those scenarios inside one test class.
Example 2 · @Nested scenarios for the cart
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.math.BigDecimal;
import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;
@DisplayName("Cart")class CartScenariosTest {
private static final BigDecimal NOTEBOOK = new BigDecimal("60.00");
private Cart cart;
@BeforeEach void createCart() { cart = new Cart(); }
@Nested @DisplayName("when empty") class WhenEmpty {
@Test @DisplayName("total is zero") void totalIsZero() { assertThat(cart.total()).isEqualByComparingTo("0"); }
@Test @DisplayName("removing a SKU is rejected") void removingIsRejected() { assertThatThrownBy(() -> cart.remove("NB-A5")).isInstanceOf(IllegalArgumentException.class); } }
@Nested @DisplayName("with two notebooks") class WithTwoNotebooks {
@BeforeEach void addTwoNotebooks() { // runs after the outer createCart() cart.add("NB-A5", NOTEBOOK, 2); }
@Test @DisplayName("total is 120.00") void totalIs120() { assertThat(cart.total()).isEqualByComparingTo("120.00"); }
@Test @DisplayName("removing the notebooks empties the cart") void removingEmpties() { cart.remove("NB-A5");
assertThat(cart.lines()).isEmpty(); } }}Cart
when empty
total is zero
removing a SKU is rejected
with two notebooks
total is 120.00
removing the notebooks empties the cart
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.083 s -- in com.shoplite.cart.CartScenariosTestWhat this code does
- Each
@Nestedclass is one scenario. For a test inWithTwoNotebooks, JUnit runs the outercreateCart()first and thenaddTwoNotebooks(), so the scenario only adds what is special about it. - The report reads like a specification: "Cart, with two notebooks, total is 120.00". Nested classes must not be
static, because they use the outer instance'scartfield.
The report shows a tree: the outer class, the scenarios, and the tests under each. Lifecycle methods of the outer class run first, then those of the nested class, so each scenario only adds what is different.
Order of execution
Order the calls in a nested scenario
Tap the steps in the order JUnit runs them for totalIs120.
@Tag, @Disabled with a reason, and running groups from Maven
@Tag labels a test or class with a name such as "slow", so that groups can be included or excluded when running. Maven Surefire reads the groups and excludedGroups properties.
Some tests are fast and some are slow. Tag them, and tell Maven which group to run.
Example 3 · @Tag, @Disabled and running groups from Maven
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
// ===== src/test/java/com/shoplite/cart/CartTaggedTest.java =====package com.shoplite.cart;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;import java.util.stream.IntStream;
import org.junit.jupiter.api.Disabled;import org.junit.jupiter.api.Tag;import org.junit.jupiter.api.Test;
class CartTaggedTest {
@Test @Tag("fast") void onePenCountsOneItem() { Cart cart = new Cart(); cart.add("PEN-BLU", new BigDecimal("10.00"), 1);
assertThat(cart.itemCount()).isEqualTo(1); }
@Test @Tag("slow") void tenThousandDifferentSkusStillTotalCorrectly() { Cart cart = new Cart(); IntStream.rangeClosed(1, 10_000).forEach(i -> cart.add("SKU-" + i, new BigDecimal("1.00"), 1));
assertThat(cart.total()).isEqualByComparingTo("10000"); }
@Test @Disabled("GST on cart lines waits for the tax rules in issue 42; enable when Cart.gst() exists") void gstIsAddedPerLine() { }}$ mvn test -Dtest=CartTaggedTest [WARNING] Tests run: 3, Failures: 0, Errors: 0, Skipped: 1, Time elapsed: 0.412 s -- in com.shoplite.cart.CartTaggedTest $ mvn test -Dtest=CartTaggedTest -Dgroups=fast [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.031 s -- in com.shoplite.cart.CartTaggedTest $ mvn test -Dtest=CartTaggedTest -DexcludedGroups=slow [WARNING] Tests run: 2, Failures: 0, Errors: 0, Skipped: 1, Time elapsed: 0.036 s -- in com.shoplite.cart.CartTaggedTest
What this code does
-Dgroups=fastran only the tagged fast test;-DexcludedGroups=slowran everything except the slow one. The disabled test is counted as Skipped, and Surefire prints that line as a warning so it stays visible.- The
@Disabledreason says what the test waits for and where to look; IDEs and reports show it next to the skipped test. A tag can also go on a whole class, for example@Tag("slow")on a class of big data tests.
mvn test -Dgroups=fast runs only the tests tagged fast, and mvn test -DexcludedGroups=slow runs everything else.
@Disabled("reason") switches a test off; it is reported as Skipped. Always write why and when it comes back ("waiting for the GST rate decision, see issue 42"); a disabled test without a reason is usually forgotten for good.
Predict the output
Which tests does Maven run?
Pick how many tests run with the command.
Round 1 of 2
Only the fast group is requested.
Test data helpers and builders
Test data builder is a small helper class that creates ready-made test objects with sensible defaults, so each test states only the values it cares about, like aCart().with("NB-A5", "60.00", 2).build().
Every test needs a cart, and each Arrange step grows longer. A builder creates carts with defaults, so a test names only what matters to it.
Example 4 · A test data builder in plain Java
import java.math.BigDecimal;import java.util.ArrayList;import java.util.Collections;import java.util.List;
record CartLine(String sku, BigDecimal unitPrice, int quantity) { public BigDecimal lineTotal() { return unitPrice.multiply(BigDecimal.valueOf(quantity)); }}
class Cart { private final List<CartLine> lines = new ArrayList<>();
public void add(String sku, BigDecimal unitPrice, int quantity) { if (quantity < 1) { throw new IllegalArgumentException("Quantity must be at least 1"); } for (int i = 0; i < lines.size(); i++) { CartLine line = lines.get(i); if (line.sku().equals(sku)) { lines.set(i, new CartLine(sku, unitPrice, line.quantity() + quantity)); return; } } lines.add(new CartLine(sku, unitPrice, quantity)); }
public void remove(String sku) { boolean removed = lines.removeIf(line -> line.sku().equals(sku)); if (!removed) { throw new IllegalArgumentException("No line for " + sku); } }
public int itemCount() { int count = 0; for (CartLine line : lines) { count += line.quantity(); } return count; }
public List<CartLine> lines() { return Collections.unmodifiableList(lines); }
public BigDecimal total() { BigDecimal total = new BigDecimal("0.00"); for (CartLine line : lines) { total = total.add(line.lineTotal()); } return total; }}
class CartBuilder { private final Cart cart = new Cart();
static CartBuilder aCart() { return new CartBuilder(); }
CartBuilder with(String sku, String unitPrice, int quantity) { cart.add(sku, new BigDecimal(unitPrice), quantity); return this; }
CartBuilder withNotebooks(int count) { // a named shortcut for a common case return with("NB-A5", "60.00", count); }
Cart build() { return cart; }}
public class CartBuilderDemo { public static void main(String[] args) { Cart empty = CartBuilder.aCart().build(); Cart notebooks = CartBuilder.aCart().withNotebooks(2).build(); Cart mixed = CartBuilder.aCart().withNotebooks(1).with("PEN-BLU", "10.00", 3).build();
System.out.println("empty: " + empty.itemCount() + " items, Rs " + empty.total()); System.out.println("notebooks: " + notebooks.itemCount() + " items, Rs " + notebooks.total()); System.out.println("mixed: " + mixed.itemCount() + " items, Rs " + mixed.total()); }}empty: 0 items, Rs 0.00 notebooks: 2 items, Rs 120.00 mixed: 4 items, Rs 90.00
What this code does
CartBuilderhides how a cart is filled: eachwithcall returns the builder, so a test describes its cart in one readable line, andwithNotebooks(2)names a case many tests need.- If
Cart.addever changes its parameters, only the builder needs fixing, not fifty tests. In a project the builder lives insrc/test/javanext to the tests.
Example 5 · Tests using the builder
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
// ===== src/test/java/com/shoplite/cart/CartBuilder.java =====package com.shoplite.cart;
import java.math.BigDecimal;
class CartBuilder { private final Cart cart = new Cart();
static CartBuilder aCart() { return new CartBuilder(); }
CartBuilder with(String sku, String unitPrice, int quantity) { cart.add(sku, new BigDecimal(unitPrice), quantity); return this; }
CartBuilder withNotebooks(int count) { return with("NB-A5", "60.00", count); }
Cart build() { return cart; }}// ===== src/test/java/com/shoplite/cart/CartTotalsWithBuilderTest.java =====package com.shoplite.cart;
import static com.shoplite.cart.CartBuilder.aCart;import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class CartTotalsWithBuilderTest {
@Test void notebooksAndPensTotal() { Cart cart = aCart().withNotebooks(1).with("PEN-BLU", "10.00", 3).build();
assertThat(cart.total()).isEqualByComparingTo("90.00"); }
@Test void removingNotebooksLeavesPens() { Cart cart = aCart().withNotebooks(2).with("PEN-BLU", "10.00", 1).build();
cart.remove("NB-A5");
assertThat(cart.itemCount()).isEqualTo(1); }}[INFO] Running com.shoplite.cart.CartTotalsWithBuilderTest [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.047 s -- in com.shoplite.cart.CartTotalsWithBuilderTest
What this code does
- With
import static ... CartBuilder.aCart, each Arrange step is one line that shows only the values that matter for the test. - The builder is named
CartBuilder, notTestCartBuilder, so Surefire'sTest*pattern does not pick it up as a test class.
Simpler helpers work too: a static method such as cartWithNotebooks(int count) in the test class. Name helpers after what they make, not Test..., so Surefire does not mistake them for test classes.
Next step
Check your understanding
10 quick questions