使用SpringRunner加快SpringBootTest的启动时间

时间:2018-01-18 18:44:02

标签: spring-boot spring-boot-test

我正在寻找一种方法来最小化SpringBootTest的启动时间,该启动时间目前需要15秒才能启动并执行测试。我已经使用了特定webEnvironment类的模拟standaloneSetup()RestController

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());
    }
}

我是否应该使用其他任何配置来加快速度?我使用Spring Boot 1.5.9。

1 个答案:

答案 0 :(得分:3)

因为您正在测试特定的控制器。因此,使用@WebMvcTest注释而不是常规测试注释@SpringBootTest可以更精细。它会快得多,因为它只会加载你的应用片段。

@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());
    }
}