Search code examples
javaunit-testingjunitjunit-jupiter

Junit BeforeAll or BeforeEach - when to initialise class under test if state does not change between tests?


In my following example I am unsure if I should use BeforeEach or BeforeAll - Note the class under test Calculator does not change state etc between tests so I assumed making it static and using BeforeEach is more efficient?

public class CalculatorShould {

    private static Calculator calculator;

    @BeforeAll
    static void setUp() {
        calculator= new Calculator();
    }

    @Test
    void calculatePriceForTwo() {

        // act
        Double price = calculator.calculatePrice(2);

        // assert
        assertEquals(10, price);
    }

    @Test
    void calculatePriceForFour() {

        // act
        Double price = calculator.calculatePrice(4);

        // assert
        assertEquals(20, price);
    }
}

Solution

  • I think in your example you don't need either BeforeAll or BeforeEach.

    Instead, it's simpler (less code is good) to just declare:

    public class CalculatorShould {
    
        private Calculator calculator = new Calculator();
    
        // test methods unchanged...
    }
    

    JUnit will provide you with a brand new instance of the Calculator before each test method is run:

    In order to allow individual test methods to be executed in isolation and to avoid unexpected side effects due to mutable test instance state, JUnit creates a new instance of each test class before executing each test method (see Test Classes and Methods). This "per-method" test instance lifecycle is the default behavior in JUnit Jupiter and is analogous to all previous versions of JUnit.

    Source: https://junit.org/junit5/docs/current/user-guide/#writing-tests-test-instance-lifecycle