使用 SpringRunner 加快 SpringBootTest 的启动时间

问题描述 投票:0回答:1

我正在寻找一种方法来最小化

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。

java spring-boot spring-boot-test
1个回答
4
投票

因为您正在测试特定的控制器。因此,您可以使用

@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());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.