Search code examples
spring-bootspring-testspringrunner

Why does @SpringRunner test reinitialize the class on each test?


I am using @PostConstruct to do some initial setup before running tests, but it seems like the @PostConstruct method is running on each and every test, instead of only once after the test class is initialized. I also see that the constructor is being called before each and every test before the @PostConstruct. Why is the test class being initialized on every @Test method instead of just once?

I am using spring-boot-starter-test:1.5.7.RELEASE

Sample test setup:

@RunWith(SpringRunner.class)
public class TestClass {

    public TestClass() {
        System.out.println("constructor");
    }

    @PostConstruct
    public void setup() {
        System.out.println("setting up");
    }

    @Test
    public void test1() {
        System.out.println("test 1");
    }

    @Test
    public void test2() {
        System.out.println("test 2");
    }
}

In the output, 'constructor' is printed twice, and 'setting up' is printed twice. 'test 1' and 'test 2' are printed once each.


Solution

  • This is the standard lifecycle for JUnit. A new instance of the class is created before each test method is called. Creating that instance requires the test class’s constructor to be called. Given that the constructor has been called, it then makes sense to call any @PostConstruct methods.