Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Writing Our First Test Methods

A test method is a method that fulfills these three requirements:

  • A test method isn't private or static
  • A test method must not return anything. In other words, its return type must be void.
  • A test method must be annotated with the @Test annotation.


Let's add two test methods to our test class:

The firstTest() method

...

and

...

 

...

secondTest() method

...

have a custom display name and

...

they write a unique string to System.out.

...

After we have written these two test methods, the source code of our test class looks as follows:


Code Block
import org.junit.jupiter.api.*;
 
@DisplayName("JUnit 5 Example")
class JUnit5ExampleTest {
 
    @BeforeAll
    static void beforeAll() {
        System.out.println("Before all test methods");
    }
 
    @BeforeEach
    void beforeEach() {
        System.out.println("Before each test method");
    }
 
    @AfterEach
    void afterEach() {
        System.out.println("After each test method");
    }
 
    @AfterAll
    static void afterAll() {
        System.out.println("After all test methods");
    }
 
// Added test methods

    @Test
    @DisplayName("First test")
    void firstTest() {
        System.out.println("First test method");
    }
 
    @Test
    @DisplayName("Second test")
    void secondTest() {
        System.out.println("Second test method");
    }
}

...