Spring Boot 跟 @WebMvcTest 测试 MVC Web Controller
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testMyController() throws Exception {
mockMvc.perform(get("/myEndpoint"))
.andDo(print())
.andExpect(status().isOk());
}
}
这段代码使用了Spring Boot的@SpringBootTest注解来启用Spring Boot的自动配置,并且使用了@AutoConfigureMockMvc注解来自动配置MockMvc。然后,它通过MockMvc发送GET请求到"/myEndpoint"并验证响应的状态是200(即OK)。这是一个简单的例子,展示了如何对Spring Boot应用中的Controller进行端到端的测试。
评论已关闭