x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    JUnit 5 BeforeEach, AfterEach annotation Example


    1. Using @BeforeEach and @AfterEach

    If you may want to initialize code before running each individual test. Instead of calling the code in each test method and to avoid duplication, you can put that code in a method with @BeforeEach annotation.

    Similarly you might want to do some cleanup activity after each test is executed. You can put this common code with method marked with @AfterEach annotation.

    In below example assume we have already written Calculator class and we do not want to create the instance for each test, we can do it in the method marked with @BeforeEach annotation.

    import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;public class CalculatorTest {        private Calculator calculator;    @BeforeEach    public void initiate() {        calculator = new Calculator();    }        @Test    public void testDivide() {        double result = calculator.divide(12, 4);        assertEquals(3, result);    }        @Test    public void testMultiply() {    	double result = calculator.multiply(3, 4);    	assertEquals(12, result);    }        @AfterEach    public void end() {        calculator = null;    }}    

    2. Using @BeforeAll and @AfterAll

    Sometimes you may want to perform some task before running all the tests e.g. starting a web server, you can do that in a method marked with@BeforeAll annotation.

    Similarly you might want to do some cleanup activity after all the tests are executed. You can put that code in a method marked with @AfterAll annotation.


    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *











    Share This