Search code examples
javaspring-bootspring-boot-test

Speed up startup time of a SpringBootTest with SpringRunner


I am looking for a way to minimize startup time of a SpringBootTest which currently takes up to 15 seconds until it is started and tests are executed. I already use the mocked webEnvironment and the standaloneSetup() of the specific RestController class.

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.MOCK;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = MOCK)
public class DataControllerMvcTests {

    @Autowired
    private DataService dataService;

    @Autowired
    private DataController dataController;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders
                .standaloneSetup(dataController)
                .build();
    }

    @Test
    @WithMockUser(roles = "READ_DATA")
    public void readData() throws Exception {
        mockMvc.perform(get("/data")).andExpect(status().is2xxSuccessful());
    }
}

Is there any other configuration I should use in order to speed it up? I use Spring Boot 1.5.9.


Solution

  • Since you are testing a particular controller. So you can be more granular by using the @WebMvcTest annotation instead of the general test annotation @SpringBootTest. It will be much faster as it will only load a slice of your app.

    @RunWith(SpringRunner.class)
    @WebMvcTest(value = DataController.class)
    public class DataControllerMvcTests {
    
        @Mock
        private DataService dataService;
    
        @Autowired
        private MockMvc mockMvc;
    
        @Before
        public void setup() {
            mockMvc = MockMvcBuilders
                    .standaloneSetup(dataController)
                    .build();
        }
    
        @Test
        public void readData() throws Exception {
            //arrange mock data
            //given( dataService.getSomething( "param1") ).willReturn( someData );
    
            mockMvc.perform(get("/data")).andExpect(status().is2xxSuccessful());
        }
    }