MockMvc

Wu Jun 2019-12-25 15:59:03
Categories: > Tags:

测试controller

初始化

SpringBoot 中很方便

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloWorldControlerTests {

    @Autowired
    private MockMvc mockMvc;
}

声明请求

MockHttpServletRequestBuilder API:

get

MockHttpServletRequestBuilder builder = get("/test")
                    .param("size", "5");

post

MockHttpServletRequestBuilder builder = post("/test")
                .header("X-Operator", OPERATOR)
                .accept(APPLICATION_JSON)
                .contentType(APPLICATION_JSON)
                .content("{ \"blockIp\": false, \"idList\": [] }");    

执行请求

ResultActions完成如下三件事:

ResultActions actions = mvc.perform(builder);

MvcResult mvcResult = actions
                .andExpect(MockMvcResultMatchers.status().is(status.value()))
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
                
MockHttpServletResponse response = mvcResult.getResponse();

测试示例

测试普通控制器

 mockMvc.perform(get("/user/{id}", 1)) //执行请求  
        .andExpect(model().attributeExists("user")) //验证存储模型数据  
        .andExpect(view().name("user/view")) //验证viewName  
        .andExpect(forwardedUrl("/WEB-INF/jsp/user/view.jsp"))//验证视图渲染时forward到的jsp  
        .andExpect(status().isOk())//验证状态码  
        .andDo(print()); //输出MvcResult到控制台  

全局配置

 mockMvc = webAppContextSetup(wac)  
        .defaultRequest(get("/user/1").requestAttr("default", true)) //默认请求 如果其是Mergeable类型的,会自动合并的哦mockMvc.perform中的RequestBuilder  
        .alwaysDo(print())  //默认每次执行请求后都做的动作  
        .alwaysExpect(request().attribute("default", true)) //默认每次执行后进行验证的断言  
        .build();