Exercise – JUnit @Before and @After annotations
Read the JUnit user guide (https://junit.org/junit5/docs/current/user-guide) and the class SampleMathTest
two new methods:
- One that is executed only once before any test method is run
- One that is executed only once after all the test methods were run
We did not talk about it, so you would need to do some research.
Answer
For JUnit 5, the annotations that can be used for this purpose are @BeforeAll
and @AfterAll
. Here is the demonstration code:
public class DemoTest { @BeforeAll static void beforeAll(){ System.out.println("beforeAll is executed"); } @AfterAll static void afterAll(){ System.out.println("afterAll is executed"); } @Test void test1(){ System.out.println("test1 is executed"); } @Test void test2(){ System.out.println("test2 is executed"); } }
If you run it, the output will be:
beforeAll is executed test1 is executed test2 is executed afterAll is executed