Before and after the class

Some setup is expensive enough that it should happen once per class rather than once per test: loading a file, starting a small server, filling a list that every test reads. JUnit has @BeforeAll and @AfterAll for that, and their rule is stricter than the per-test pair: the method is static by default.

One list for the class

NamesTest.java keeps a static list. @BeforeAll creates it and adds one name; two tests read it; @AfterAll clears it. Neither test changes the list, so the shared state is read-only from the tests' point of view.

import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; public class NamesTest { private static List<String> names; @BeforeAll static void createList() { names = new ArrayList<>(); names.add("Ada"); } @AfterAll static void clearList() { names.clear(); } @Test void listHasOneName() { assertEquals(1, names.size()); } @Test void listHasAda() { assertEquals("Ada", names.get(0)); } }

@BeforeAll and the static rule

@BeforeAll runs once before the first test of the class. The method must be static, because Jupiter calls it on the class before it knows which instance will run. Remove static and the launcher reports java.lang.IllegalStateException: Non-static @BeforeAll method ... must be static unless the test class is annotated with @TestInstance(PER_CLASS). The next lesson on the per-class lifecycle removes the restriction instead of the annotation.

The static rule has a price: a static field outlives the class object and is shared by every test in the class. A test that writes to it changes what the next test reads, and the order of tests is not guaranteed. The safe shape is a value that is built once and never changed, or a resource that every test opens in its own way.

@AfterAll

@AfterAll runs once after the last test, and it is also static by default. It is the place to close a shared file, stop a server or clear the static list. Like the per-test after method, it runs after a red test as well as a green one, so the cleanup is not skipped because one test failed.

A class-level failure

If @BeforeAll throws, no test of the class runs. The report shows the class with a cross and the exception, and the counts table shows the tests as found but not started. That is a different shape from a failed test: the tests did not run, so their own assertions never had a chance to pass or fail.

The report

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out NamesTest.java
junit execute --class-path out --scan-classpath --disable-ansi-colors

Thanks for using JUnit! Support its development at https://junit.org/sponsoring

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│  └─ NamesTest ✔
│     ├─ listHasOneName() ✔
│     └─ listHasAda() ✔
└─ JUnit Vintage ✔

Test run finished after 1027 ms
[         4 containers found      ]
[         0 containers skipped    ]
[         4 containers started    ]
[         0 containers aborted    ]
[         4 containers successful ]
[         0 containers failed     ]
[         2 tests found           ]
[         0 tests skipped         ]
[         2 tests started         ]
[         0 tests aborted         ]
[         2 tests successful      ]
[         0 tests failed          ]

Both tests read the list the class method built. The report does not count the two class-level methods; it counts the two tests. The time line is longer than the previous lesson only because this run loaded a list and the JVM started again.

Exercises

  1. Remove static from createList and run. Copy the exception line into your notes.
  2. Add a test that appends a name to the list and run the class twice. Does the second run see the appended name? Why or why not?
  3. Make createList throw a RuntimeException and read the counts: how many tests started?
  4. Move the list creation into @BeforeEach and compare the two reports. Which setup does this class need?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How often does @BeforeAll run?

    Answer

    Once before the first test of the class

    The class-level method runs once, before the first test, and the after-all runs once at the end.

  2. Why must @BeforeAll be static by default?

    Answer

    Jupiter calls it on the class before it creates a test instance

    The default lifecycle creates an instance per test, so a class-level method has no instance to belong to.

  3. What happens when @BeforeAll throws?

    Answer

    No test of the class runs; the report shows a class-level failure

    The setup failed before any test, so the tests are found but not started.

  4. What does this program print? public class Q1 { public static void main(String[] args) { java.util.List<String> names = new java.util.ArrayList<>(); names.add("Ada"); names.add("Grace"); System.out.println(names.size()); } }

    Answer

    2

    Two names were added, so the list has two elements.

  5. What does this program print? public class Q2 { public static void main(String[] args) { java.util.List<String> names = new java.util.ArrayList<>(); names.add("Ada"); System.out.println(names.get(0)); } }

    Answer

    Ada

    get(0) returns the first element, which is Ada.

  6. What does this program print? public class Q3 { static int count = 3; public static void main(String[] args) { count = count * 2; System.out.println(count); } }

    Answer

    6

    The assignment doubles 3, and println prints 6.

  7. What does this program print? public class Q4 { public static void main(String[] args) { java.util.List<String> names = new java.util.ArrayList<>(); names.add("Ada"); names.clear(); System.out.println(names.size()); } }

    Answer

    0

    clear removes every element, so the size is 0.

  8. Why is a mutable static field in a test class risky?

    Answer

    One test can change what the next test reads, and the order is not guaranteed

    The field lives for the whole class, so state leaks between tests.

  9. What does this program print? public class Q5 { public static void main(String[] args) { String a = "Ada"; String b = a; b = "Grace"; System.out.println(a); } }

    Answer

    Ada

    The second assignment changes the reference b, not the string a points to.

  10. Which pair of methods runs once for the whole class?

    Answer

    @BeforeAll and @AfterAll

    The all methods bracket the class; the each methods bracket every test.

The code on this page was built with OpenJDK 21.0.13 (javac) and run with JUnit Platform Console Launcher 1.14.3 on Alpine Linux in a Docker container.

Article author: Arthur Isaev