2017-04-12 56 views
1
@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"); 
    } 
} 

主類:爲什麼MockMvc不能在春天開機測試@WebServlet

@SpringBootApplication 
@ServletComponentScan 
public class Demo20Application { 

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

測試代碼:

@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 

這個servlet發送200個狀態碼,但測試結果表明我狀態是404

似乎MockMvc不能用於在彈簧啓動時測試servlet

回答

1

MockMvc用於測試控制器(即,您定義了一個@Controller的組件,其中有一些方法使用@RequestMapping)。 MockMvc允許你測試你的web層,而無需啓動一個servlet容器併爲你模擬servlet上下文。

您正在創建一個完全在此環境之外的原始servlet。所以,不,這不被支持。