Junior
What annotations for fixtures exist in JUnit?
sobes.tech AI
Answer from AI
Annotations for fixtures in JUnit 4 and JUnit 5 differ:
JUnit 4:
@BeforeClass: Method runs once before all test methods in the class. Must be static.@AfterClass: Method runs once after all test methods in the class. Must be static.@Before: Method runs before each test method.@After: Method runs after each test method.
JUnit 5:
@BeforeAll: Used to annotate methods that should be executed before all test methods in the current class. Similar to@BeforeClassin JUnit 4, but does not require a static method if the class is annotated with@TestInstance(Lifecycle.PER_CLASS).@AfterAll: Used to annotate methods that should be executed after all test methods in the current class. Similar to@AfterClassin JUnit 4.@BeforeEach: Used to annotate methods that should be executed before each test method. Similar to@Beforein JUnit 4.@AfterEach: Used to annotate methods that should be executed after each test method. Similar to@Afterin JUnit 4.
Example of usage in JUnit 5:
// Example of using fixture annotations in JUnit 5
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class FixtureExampleTest {
@BeforeAll
static void setupAll() {
// Code that runs once before all tests
System.out.println("@BeforeAll executed");
}
@BeforeEach
void setupEach() {
// Code that runs before each test
System.out.println("@BeforeEach executed");
}
@Test
void testMethod1() {
System.out.println("Executing testMethod1()");
assertTrue(true);
}
@Test
void testMethod2() {
System.out.println("Executing testMethod2()");
assertTrue(true);
}
@AfterEach
void cleanupEach() {
// Code that runs after each test
System.out.println("@AfterEach executed");
}
@AfterAll
static void cleanupAll() {
// Code that runs once after all tests
System.out.println("@AfterAll executed");
}
}