2.2. Test Classes and Methods

Test Class: any top-level class, static member class, or @Nested class that contains at least one test method.

Test classes must not be abstract and must have a single constructor.

Test Method: any instance method that is directly annotated or meta-annotated with @Test, @RepeatedTest, @ParameterizedTest, @TestFactory, or @TestTemplate.

Lifecycle Method: any method that is directly annotated or meta-annotated with @BeforeAll, @AfterAll, @BeforeEach, or @AfterEach.

Test methods and lifecycle methods may be declared locally within the current test class, inherited from superclasses, or inherited from interfaces (see Test Interfaces and Default Methods). In addition, test methods and lifecycle methods must not be abstract and must not return a value.

Test classes, test methods, and lifecycle methods are not required to be public, but they must not be private.

The following test class demonstrates the use of @Test methods and all supported lifecycle methods. For further information on runtime semantics, see Test Execution Order and Wrapping Behavior of Callbacks.

A standard test class

  1. import static org.junit.jupiter.api.Assertions.fail;
  2. import static org.junit.jupiter.api.Assumptions.assumeTrue;
  3. import org.junit.jupiter.api.AfterAll;
  4. import org.junit.jupiter.api.AfterEach;
  5. import org.junit.jupiter.api.BeforeAll;
  6. import org.junit.jupiter.api.BeforeEach;
  7. import org.junit.jupiter.api.Disabled;
  8. import org.junit.jupiter.api.Test;
  9. class StandardTests {
  10. @BeforeAll
  11. static void initAll() {
  12. }
  13. @BeforeEach
  14. void init() {
  15. }
  16. @Test
  17. void succeedingTest() {
  18. }
  19. @Test
  20. void failingTest() {
  21. fail("a failing test");
  22. }
  23. @Test
  24. @Disabled("for demonstration purposes")
  25. void skippedTest() {
  26. // not executed
  27. }
  28. @Test
  29. void abortedTest() {
  30. assumeTrue("abc".contains("Z"));
  31. fail("test should have been aborted");
  32. }
  33. @AfterEach
  34. void tearDown() {
  35. }
  36. @AfterAll
  37. static void tearDownAll() {
  38. }
  39. }