gpt4 book ai didi

java - 如何为 Spring Boot Controller 端点编写单元测试

转载 作者:IT老高 更新时间:2023-10-28 13:52:51 25 4
gpt4 key购买 nike

我有一个带有以下内容的示例 Spring Boot 应用程序

引导主类

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

Controller

@RestController
@EnableAutoConfiguration
public class HelloWorld {
@RequestMapping("/")
String gethelloWorld() {
return "Hello World!";
}

}

为 Controller 编写单元测试最简单的方法是什么?我尝试了以下方法,但它提示无法 Autowiring WebApplicationContext

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
public class DemoApplicationTests {

final String BASE_URL = "http://localhost:8080/";

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}

@Test
public void testSayHelloWorld() throws Exception{

this.mockMvc.perform(get("/")
.accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"));
}

@Test
public void contextLoads() {
}

}

最佳答案

Spring MVC 提供了一个 standaloneSetup支持测试相对简单的 Controller ,无需上下文。

Build a MockMvc by registering one or more @Controller's instances andconfiguring Spring MVC infrastructure programmatically. This allowsfull control over the instantiation and initialization of controllers,and their dependencies, similar to plain unit tests while also makingit possible to test one controller at a time.

Controller 的示例测试可以很简单

public class DemoApplicationTests {

private MockMvc mockMvc;

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

@Test
public void testSayHelloWorld() throws Exception {
this.mockMvc.perform(get("/")
.accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"));

}
}

关于java - 如何为 Spring Boot Controller 端点编写单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29053974/

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