Test Lifecycle Methods - anastasiamexa/Healthy-Coder-App GitHub Wiki

In JUnit 5, @BeforeEach, @AfterEach, @BeforeAll, and @AfterAll are annotations used to define setup and teardown methods in your test classes. These annotations help you manage the test environment and the state before and after test methods are executed.

@BeforeEach

  • Purpose: Marks a method to be run before each test method in the class.
  • Usage: Use @BeforeEach to set up the initial state or perform actions that are common to all test methods in the class.
import org.junit.jupiter.api.BeforeEach;

public class MyTest {

    @BeforeEach
    void setUp() {
        // Initialization code before each test
    }

    // Test methods go here
}

@AfterEach

  • Purpose: Marks a method to be run after each test method in the class.
  • Usage: Use @AfterEach to clean up resources, reset states, or perform actions needed after each test method.
import org.junit.jupiter.api.AfterEach;

public class MyTest {

    @AfterEach
    void tearDown() {
        // Cleanup code after each test
    }

    // Test methods go here
}

@BeforeAll

  • Purpose: Marks a method to be run once before any of the test methods in the class.
  • Usage: Use @BeforeAll for setup tasks that are shared across all test methods in the class.
  • Constraints: The method must be static.
import org.junit.jupiter.api.BeforeAll;

public class MyTest {

    @BeforeAll
    static void setUpClass() {
        // Initialization code before all tests
    }

    // Test methods go here
}

@AfterAll

  • Purpose: Marks a method to be run once after all the test methods in the class have been executed.
  • Usage: Use @AfterAll for cleanup tasks or actions that should occur after all tests have run.
  • Constraints: The method must be static.
import org.junit.jupiter.api.AfterAll;

public class MyTest {

    @AfterAll
    static void tearDownClass() {
        // Cleanup code after all tests
    }

    // Test methods go here
}

These annotations provide a convenient way to manage the test environment and ensure that the setup and cleanup code is executed consistently before and after your test methods. They contribute to making your tests more modular, maintainable, and predictable.