如何为 Spring Boot 控制器终结点编写单元测试
2022-08-31 12:38:41
我有一个示例Spring Boot应用程序,其中包含以下内容
引导主类
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
控制器
@RestController
@EnableAutoConfiguration
public class HelloWorld {
@RequestMapping("/")
String gethelloWorld() {
return "Hello World!";
}
}
为控制器编写单元测试的最简单方法是什么?我尝试了以下方法,但它抱怨无法自动连接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() {
}
}