Skip to lesson

Test structure: Arrange, Act, Assert

ShopLite works, but every change might break it. A test proves a rule still holds, and a good test is one anyone can read in seconds.

A test class and @Test methods

@Test is the JUnit 5 annotation that marks a method as one test. JUnit finds every @Test method of a test class, creates a new object of the class for each one and calls it; the test passes if the method returns and fails if it throws.

ShopLite works, but nothing proves it yet. First see what JUnit does for you: it finds the @Test methods and runs each on a fresh object. A tiny runner of our own shows the idea, then comes a real test.

Example 1 · What JUnit does for you: find @Test methods, one fresh object each

TinyTestRunner.javaJava
import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.Arrays;import java.util.Comparator;
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@interface Test {                        // our own marker, like JUnit's @Test}
class GstTest {    static int created = 0;
    GstTest() {        created++;                       // count how many test objects are made    }
    @Test    void gstOn100Is18() {        check(18, 100 * 18 / 100);    }
    @Test    void gstOn250Is45() {        check(45, 250 * 18 / 100);    }
    void notATest() {        throw new IllegalStateException("never called: no @Test");    }
    static void check(int expected, int actual) {        if (expected != actual) {            throw new AssertionError("expected: <" + expected + "> but was: <" + actual + ">");        }    }}
public class TinyTestRunner {    public static void main(String[] args) throws Exception {        Method[] methods = GstTest.class.getDeclaredMethods();        Arrays.sort(methods, Comparator.comparing(Method::getName));    // a fixed order for this demo
        int run = 0;        int failed = 0;        for (Method method : methods) {            if (!method.isAnnotationPresent(Test.class)) {                continue;            }            Object freshInstance = GstTest.class.getDeclaredConstructor().newInstance();            run++;            try {                method.invoke(freshInstance);                System.out.println("PASS " + method.getName());            } catch (InvocationTargetException e) {                failed++;                System.out.println("FAIL " + method.getName() + ": " + e.getCause().getMessage());            }        }        System.out.println("Tests run: " + run + ", Failures: " + failed + ", test objects created: " + GstTest.created);    }}
Output
PASS gstOn100Is18
PASS gstOn250Is45
Tests run: 2, Failures: 0, test objects created: 2

What this code does

  • This runner does in 30 lines what JUnit does for real: it looks at every method, keeps only those carrying the @Test marker (so notATest is never called) and runs each one.
  • It creates a new GstTest object for every test method, which is why 2 objects were made. JUnit does the same, so a field set in one test is never seen by another test.

Example 2 · The class under test: Cart

CartDemo.javaJava
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;    }}
public class CartDemo {    public static void main(String[] args) {        Cart cart = new Cart();        cart.add("NB-A5", new BigDecimal("60.00"), 3);        cart.add("PEN-BLU", new BigDecimal("10.00"), 5);        cart.add("NB-A5", new BigDecimal("60.00"), 1);
        System.out.println("Lines: " + cart.lines());        System.out.println("Items: " + cart.itemCount());        System.out.println("Total: Rs " + cart.total());    }}
Output
Lines: [CartLine[sku=NB-A5, unitPrice=60.00, quantity=4], CartLine[sku=PEN-BLU, unitPrice=10.00, quantity=5]]
Items: 9
Total: Rs 290.00

What this code does

  • Cart is the ShopLite basket this module tests: add merges lines with the same SKU, itemCount adds the quantities and total adds the line totals as BigDecimal, starting from 0.00.
  • In shoplite-api the two types live in src/main/java/com/shoplite/cart/ as public Cart.java and CartLine.java; here they are in one file so you can run them. Its rules (no quantity below 1, merging lines) are what the tests will pin down.

Example 3 · A first JUnit test class

Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)

Java
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class CartTest {
    @Test    void aNewCartIsEmpty() {        Cart cart = new Cart();
        assertEquals(0, cart.itemCount());    }}
Sample output
$ mvn test -Dtest=CartTest
...
[INFO] Running com.shoplite.cart.CartTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.034 s -- in com.shoplite.cart.CartTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

What this code does

  • The class and method have no public, the test is in the same package as Cart, and assertEquals is imported statically from org.junit.jupiter.api.Assertions so it reads like plain English.
  • There is no main: Surefire finds CartTest by its name and JUnit runs the @Test method, exactly like the tiny runner in Example 1.

A test class is an ordinary class in src/test/java, named after the class it tests plus Test (CartTest for Cart). The class and its methods need no public: package-private (no access word) is the normal style, because only JUnit calls them.

A test method returns void, takes no arguments and must not be private or static. There is no main: JUnit finds the tests and creates a new object of the test class for every test method.

Predict the output

Which methods does JUnit run?

Read the test class, then pick how many tests JUnit runs.

Round 1 of 2

JUnit runs a class with three methods.

class PriceTest {
@Test
void tenPercentOf200Is20() { ... }
@Test
public void taxOn100Is18() { ... }
void helperWithoutTest() { ... }
}

Arrange, Act, Assert

Arrange, Act, Assert (AAA) is the standard shape of a test. Arrange creates the objects and data the test needs, Act calls the one method being tested, and Assert compares the result with the expected value.

Here are three tests for Cart. Each one builds a cart, calls one method and then checks the result, always in that order.

A JUnit test has three parts. Arrange builds what the test needs: a new Cart with 3 notebooks at 60.00. Act calls the one method being tested: cart.total(). Assert compares the expected value with the actual one: assertEquals(new BigDecimal("180.00"), total).

Example 4 · Three tests in Arrange, Act, Assert form

Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)

Java
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
class CartTest {
    @Test    void addingTwoNotebooksCountsTwoItems() {        // Arrange        Cart cart = new Cart();
        // Act        cart.add("NB-A5", new BigDecimal("60.00"), 2);
        // Assert        assertEquals(2, cart.itemCount());    }
    @Test    void addingTheSameSkuAgainIncreasesTheQuantity() {        Cart cart = new Cart();        cart.add("NB-A5", new BigDecimal("60.00"), 1);
        cart.add("NB-A5", new BigDecimal("60.00"), 2);
        assertEquals(3, cart.lines().get(0).quantity());    }
    @Test    void totalAddsEveryLine() {        Cart cart = new Cart();        cart.add("NB-A5", new BigDecimal("60.00"), 3);        cart.add("PEN-BLU", new BigDecimal("10.00"), 5);
        BigDecimal total = cart.total();
        assertEquals(new BigDecimal("230.00"), total);    }}
Sample output
[INFO] Running com.shoplite.cart.CartTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.041 s -- in com.shoplite.cart.CartTest

What this code does

  • The first test labels its three parts. The others keep the same shape with blank lines only: set up the cart, call add or total once, then assert.
  • The expected values come from the rules, worked out by hand: 3 × 60.00 + 5 × 10.00 = 230.00. Writing new BigDecimal("230.00") with two decimals matters, because BigDecimal.equals also compares the number of decimals (the Core assertions lesson covers this).

Keep the three parts visible: separate them with a blank line, and in your first tests label them with // Arrange, // Act and // Assert comments. The Act part is usually one line. If Arrange grows long, the class under test may be doing too much, or you need a helper method.

Order of execution

Order the steps of one test

Tap the steps in the order the test does them.

@Test
void totalAddsEveryLine() {
Cart cart = new Cart();
cart.add("NB-A5", new BigDecimal("60.00"), 3);
cart.add("PEN-BLU", new BigDecimal("10.00"), 5);
BigDecimal total = cart.total();
assertEquals(new BigDecimal("230.00"), total);
}
assertEquals takes the expected value first, then the actual one. Swapping them still passes or fails correctly, but the failure message then lies about which value was expected.

One reason to fail per test

One reason to fail means a test checks one behaviour, so a red test tells you exactly which promise broke. Several assertions are fine when they describe that same behaviour, such as the quantity and the total after one add.

Compare one big test with several small ones. The big test can break for three different reasons; each small test can break for only one.

Example 5 · Several reasons to fail in one test, and the fix

Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)

Java
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
class CartRulesTest {
    // Bad: three unrelated rules; the first failure hides the rest    @Test    void cartWorks() {        Cart cart = new Cart();        cart.add("NB-A5", new BigDecimal("60.00"), 2);        assertEquals(2, cart.itemCount());        cart.remove("NB-A5");        assertEquals(0, cart.lines().size());        cart.add("PEN-BLU", new BigDecimal("10.00"), 4);        assertEquals(new BigDecimal("40.00"), cart.total());    }
    // Good: one behaviour each, so each failure names its rule    @Test    void removingASkuDeletesItsLine() {        Cart cart = new Cart();        cart.add("NB-A5", new BigDecimal("60.00"), 2);
        cart.remove("NB-A5");
        assertEquals(0, cart.lines().size());    }
    @Test    void totalIsPriceTimesQuantity() {        Cart cart = new Cart();
        cart.add("PEN-BLU", new BigDecimal("10.00"), 4);
        assertEquals(new BigDecimal("40.00"), cart.total());    }}
Sample output
[INFO] Running com.shoplite.cart.CartRulesTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.038 s -- in com.shoplite.cart.CartRulesTest

What this code does

  • cartWorks acts three times and asserts three unrelated things. If remove broke, the report would say only cartWorks failed, and the total check after it would never run.
  • The split tests each act once and check one rule, and their names are the rules. Two assertions about the same behaviour (for example the quantity and the line total after one add) would still be one reason to fail.

A failed assertion throws an exception and ends the test at once, so any later assertions in it never run. One big test with ten unrelated checks reports only the first broken rule and hides the rest.

Find the bug

Find the second reason to fail

Each test checks two behaviours. Tap the line where the second one starts.

This test is named for adding, but it also tests removing.

Round 1 of 2

Reading a failure: expected, actual and the stack line

AssertionFailedError is the exception JUnit throws when an assertion fails. Its message shows the expected and the actual value, like expected: <3> but was: <1>, and its stack trace shows the line of your test where it happened.

This test fails because of a bug in Cart.add. Read the report from the top and follow the clues to the bug.

Example 6 · Reading a real failure

Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart), with a bug in Cart.add

Java
// The bug in Cart.add: it stores `quantity` instead of `line.quantity() + quantity`
@Testvoid addingTheSameSkuAgainIncreasesTheQuantity() {    Cart cart = new Cart();    cart.add("NB-A5", new BigDecimal("60.00"), 1);
    cart.add("NB-A5", new BigDecimal("60.00"), 2);
    assertEquals(3, cart.lines().get(0).quantity());   // line 30}
Sample output
[INFO] Running com.shoplite.cart.CartTest
[ERROR] Tests run: 3, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.056 s <<< FAILURE! -- in com.shoplite.cart.CartTest
[ERROR] com.shoplite.cart.CartTest.addingTheSameSkuAgainIncreasesTheQuantity -- Time elapsed: 0.009 s <<< FAILURE!
org.opentest4j.AssertionFailedError: expected: <3> but was: <2>
	at org.junit.jupiter.api.AssertionFailureBuilder.build(AssertionFailureBuilder.java:151)
	at org.junit.jupiter.api.AssertionFailureBuilder.buildAndThrow(AssertionFailureBuilder.java:132)
	at org.junit.jupiter.api.AssertEquals.failNotEqual(AssertEquals.java:197)
	at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:150)
	at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:145)
	at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:531)
	at com.shoplite.cart.CartTest.addingTheSameSkuAgainIncreasesTheQuantity(CartTest.java:30)
	...
[INFO] Results:
[ERROR] Failures:
[ERROR]   CartTest.addingTheSameSkuAgainIncreasesTheQuantity:30 expected: <3> but was: <2>
[ERROR] Tests run: 3, Failures: 1, Errors: 0, Skipped: 0
[INFO] BUILD FAILURE

What this code does

  • Read it top down: the test name says "adding the same SKU again increases the quantity", the message says the quantity was 2, not 3, and the stack line CartTest.java:30 (the first line in com.shoplite) points at the assertion. The six org.junit lines above it are JUnit's own and can be skipped.
  • 2 instead of 3 means the second add (quantity 2) replaced the first one: that leads straight to the bug in Cart.add. The summary at the end repeats every failure as Class.method:line message, a quick list when several tests break.

A stack trace is the chain of method calls that led to the failure; Surefire prints it with the failing test's name and the message. Read a failure in three steps:

  • The test name: which behaviour broke (a good name makes this enough on its own).
  • Expected versus actual: what the code returned instead.
  • The first stack line in your package (at com.shoplite...): the file and line of the failing assertion. The org.junit... lines above it are JUnit's own code; skip them.

Next step

Check your understanding

10 quick questions