2

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.

Hung Tran
  • 73
  • 1
  • 5

1 Answers1

5

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.

Andy Wilkinson
  • 108,729
  • 24
  • 257
  • 242
  • 1
    Wow, I didn't know this at all. I've been trying to find an explanation for this but couldn't find it anywhere. I initially thought that the class was instantiated once and each @Test method would then be sequentially called within the instance. Well now that I know this is the standard lifecycle for JUnit, it makes perfect sense. Thanks! – Hung Tran Sep 30 '17 at 07:04