gpt4 book ai didi

spring-boot - 使用 SpringRunner 加快 SpringBootTest 的启动时间

转载 作者:行者123 更新时间:2023-12-03 23:17:13 27 4
gpt4 key购买 nike

我正在寻找一种方法来最小化 SpringBootTest 的启动时间目前最多需要 15 秒才能启动并执行测试。我已经使用了模拟 webEnvironmentstandaloneSetup()具体的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());
}
}

为了加快速度,我还应该使用其他配置吗?我使用 Spring Boot 1.5.9。

最佳答案

由于您正在测试特定的 Controller 。因此,您可以通过使用 @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());
}
}

关于spring-boot - 使用 SpringRunner 加快 SpringBootTest 的启动时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48328252/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com