Search code examples
spring-bootspring-boot-test

@SpringBootTest constructor is running multiple times


I am trying to run below test case in Spring Boot.

:: Spring Boot :: (v2.3.1.RELEASE)

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

@SpringBootTest(
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
        classes = com.dineoutsafe.api.dosadmin.DOSAdminAPIApplication.class)
@ActiveProfiles("test")
public class POSTSessionTest {

    public POSTSessionTest() {
        System.out.println("Calling post construct");
    }
    @Test
    public void testOne(){
        assertThat(45,equalTo(30+15));
    }
    @Test
    public void testTwo(){
        assertThat(45,equalTo(30+15));
    }
    @Test
    public void testThree(){
        assertThat(45,equalTo(30+15));
    }
    @Test
    public void testFour(){
        assertThat(45,equalTo(30+15));
    }
    @Test
    public void testFive(){
        assertThat(45,equalTo(30+15));
    }
}

And I noticed that the constructor is running multiple times. Actually it is running (no. of @Test -1) times. In standard output

2020-06-21 16:00:26.668  INFO 93912 --- [         task-1] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-06-21 16:00:26.679  INFO 93912 --- [         task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-06-21 16:00:27.025  INFO 93912 --- [    Test worker] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-06-21 16:00:27.034  INFO 93912 --- [    Test worker] c.d.a.d.i.session.POSTSessionTest        : Started POSTSessionTest in 5.511 seconds (JVM running for 6.414)
Calling post construct
Calling post construct
Calling post construct
Calling post construct

Same behaviour I noticed for @PostConstruct. Is it normal for @SpringBootTest?


Solution

  • This is the default behavior of JUnit5, you can change it by annotating the per-class lifecycle on the class: https://junit.org/junit5/docs/5.0.1/api/org/junit/jupiter/api/TestInstance.Lifecycle.html