Spring boot 为什么MockMvc不能在spring boot中测试@WebServlet
主要类别:Spring boot 为什么MockMvc不能在spring boot中测试@WebServlet,spring-boot,Spring Boot,主要类别: @WebServlet(urlPatterns = "/test") public class TestWebServlet extends HttpServlet{ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(200);
@WebServlet(urlPatterns = "/test")
public class TestWebServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setStatus(200);
resp.getWriter().println("test");
}
}
测试代码:
@SpringBootApplication
@ServletComponentScan
public class Demo20Application {
public static void main(String[] args) {
SpringApplication.run(Demo20Application.class, args);
}
}
servlet发送200状态代码,但测试结果显示状态为404
MockMvc似乎不能用于测试spring boot中的servlet
MockMvc
用于测试控制器(即,您定义的@Controller
的组件,其上有一些带有@RequestMapping
的方法)。MockMvc允许您在不启动servlet容器的情况下测试web层,并为您模拟servlet上下文
您正在完全在此环境之外创建一个原始servlet。因此,不,这是不受支持的
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class Demo20ApplicationTests {
@Autowired
private MockMvc mockMvc;
@Test
public void testMockMvc() throws Exception {
this.mockMvc.perform(post("/test"))
.andExpect(status().isOk());
}
}
java.lang.AssertionError: Status
Expected :200
Actual :404