MockMvcBuilder |
MockHttpServletRequestBuilder |
|
|
|
|
MockHttpServletRequestBuilder header(String name, Object... values)/MockHttpServletRequestBuilder headers(HttpHeaders httpHeaders) |
添加头信息; |
|
|
MockHttpServletRequestBuilder contentType(MediaType mediaType) |
:指定请求的contentType头信息; |
|
|
MockHttpServletRequestBuilder accept(MediaType... mediaTypes)/MockHttpServletRequestBuilder accept(String... mediaTypes) |
:指定请求的Accept头信息; |
|
|
MockHttpServletRequestBuilder content(byte[] content)/MockHttpServletRequestBuilder content(String content) |
:指定请求Body体内容; |
|
|
MockHttpServletRequestBuilder cookie(Cookie... cookies) |
:指定请求的Cookie; |
|
|
MockHttpServletRequestBuilder locale(Locale locale) |
:指定请求的Locale; |
|
|
MockHttpServletRequestBuilder characterEncoding(String encoding) |
:指定请求字符编码; |
|
|
MockHttpServletRequestBuilder requestAttr(String name, Object value) |
:设置请求属性数据; |
|
|
MockHttpServletRequestBuilder sessionAttr(String name, Object value)/MockHttpServletRequestBuilder sessionAttrs(Map |
:设置请求session属性数据; |
|
|
MockHttpServletRequestBuilder flashAttr(String name, Object value)/MockHttpServletRequestBuilder flashAttrs(Map |
:指定请求的flash信息,比如重定向后的属性信息; |
|
|
MockHttpServletRequestBuilder session(MockHttpSession session) |
:指定请求的Session; |
|
|
MockHttpServletRequestBuilder principal(Principal principal) |
:指定请求的Principal; |
|
|
MockHttpServletRequestBuilder contextPath(String contextPath) |
:指定请求的上下文路径,必须以“/”开头,且不能以“/”结尾; |
|
|
MockHttpServletRequestBuilder pathInfo(String pathInfo) |
:请求的路径信息,必须以“/”开头; |
|
|
MockHttpServletRequestBuilder secure(boolean secure) |
:请求是否使用安全通道; |
|
|
MockHttpServletRequestBuilder with(RequestPostProcessor postProcessor) |
:请求的后处理器,用于自定义一些请求处理的扩展点; |
|
MockMultipartHttpServletRequestBuilder |
继承自MockHttpServletRequestBuilder,又提供了如下API: |
|
|
|
MockMultipartHttpServletRequestBuilder file(String name, byte[] content)/MockMultipartHttpServletRequestBuilder file(MockMultipartFile file) |
:指定要上传的文件; |
MockMvcBuilders |
MockHttpServletRequestBuilder get(String urlTemplate, Object... urlVariables) |
根据uri模板和uri变量值得到一个GET请求方式的MockHttpServletRequestBuilder;如get("/user/{id}", 1L); |
|
|
MockHttpServletRequestBuilder post(String urlTemplate, Object... urlVariables) |
POST |
|
|
MockHttpServletRequestBuilder put(String urlTemplate, Object... urlVariables) |
同get类似,但是是PUT方法; |
|
|
MockHttpServletRequestBuilder delete(String urlTemplate, Object... urlVariables) |
:同get类似,但是是DELETE方法; |
|
|
MockHttpServletRequestBuilder options(String urlTemplate, Object... urlVariables) |
:同get类似,但是是OPTIONS方法; |
|
|
MockHttpServletRequestBuilder request(HttpMethod httpMethod, String urlTemplate, Object... urlVariables) |
:提供自己的Http请求方法及uri模板和uri变量,如上API都是委托给这个API; |
|
|
MockMultipartHttpServletRequestBuilder fileUpload(String urlTemplate, Object... urlVariables) |
提供文件上传方式的请求,得到MockMultipartHttpServletRequestBuilder; |
|
|
RequestBuilder asyncDispatch(final MvcResult mvcResult) |
:创建一个从启动异步处理的请求的MvcResult进行异步分派的RequestBuilder; |
|
MockMvcBuilder/MockMvcBuilders API |
StandaloneMockMvcBuilder |
setMessageConverters(HttpMessageConverter>...messageConverters) |
设置HTTP消息转换器; |
|
|
setValidator(Validator validator) |
设置验证器; |
|
|
setConversionService(FormattingConversionService conversionService) |
设置转换服务; |
|
|
addInterceptors(HandlerInterceptor... interceptors)/addMappedInterceptors(String[] pathPatterns, HandlerInterceptor... interceptors) |
添加spring mvc拦截器 |
|
|
setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) |
设置内容协商管理器; |
|
|
setAsyncRequestTimeout(long timeout) |
设置异步超时时间; |
|
|
setCustomArgumentResolvers(HandlerMethodArgumentResolver... argumentResolvers) |
设置自定义控制器方法参数解析器 |
|
|
setCustomReturnValueHandlers(HandlerMethodReturnValueHandler... handlers) |
设置自定义控制器方法返回值处理器 |
|
|
setHandlerExceptionResolvers(List |
设置异常解析器 |
|
|
setViewResolvers(ViewResolver...resolvers) |
设置视图解析器 |
|
|
setSingleView(View view) |
设置单个视图,即视图解析时总是解析到这一个(仅适用于只有一个视图的情况) |
|
|
setLocaleResolver(LocaleResolver localeResolver) |
设置Local解析器 |
|
|
setFlashMapManager(FlashMapManager flashMapManager) |
设置FlashMapManager,如存储重定向数据; |
|
|
setUseSuffixPatternMatch(boolean useSuffixPatternMatch) |
设置是否是后缀模式匹配,如“/user”是否匹配"/user.*",默认真即匹配; |
|
|
addPlaceHolderValue(String name, String value) |
添加request mapping中的占位符替代; |
|
DefaultMockMvcBuilder |
addFilters(Filter... filters)/addFilter(Filter filter, String... urlPatterns) |
添加javax.servlet.Filter过滤器 |
|
|
defaultRequest(RequestBuilder requestBuilder) |
默认的RequestBuilder,每次执行时会合并到自定义的RequestBuilder中,即提供公共请求数据的 |
|
|
alwaysExpect(ResultMatcher resultMatcher) |
定义全局的结果验证器,即每次执行请求时都进行验证的规则; |
|
|
alwaysDo(ResultHandler resultHandler) |
定义全局结果处理器,即每次请求时都进行结果处理 |
|
|
dispatchOptions:DispatcherServlet |
是否分发OPTIONS请求方法到控制器 |
MockMvc |
perform |
执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; |
|
|
ResultActions
MockMvc.perform(RequestBuilder requestBuilder) |
ResultActions andExpect(ResultMatcher matcher) |
:添加验证断言来判断执行请求后的结果是否是预期的 |
|
|
ResultActions andDo(ResultHandler handler) |
添加结果处理器,用于对验证成功后执行的动作,如输出下请求/结果信息用于调试; |
|
|
MvcResult andReturn() |
;用于自定义验证/下一步的异步处理; |
|
andExpect |
添加ResultMatcher验证规则,验证控制器执行完成后结果是否正确; |
|
|
andDo |
添加ResultHandler结果处理器,比如调试时打印结果到控制台; |
|
|
andReturn |
最后返回相应的MvcResult;然后进行自定义验证/进行下一步的异步处理 |
|
|
setDefaultRequest |
设置默认的RequestBuilder,用于在每次perform执行相应的RequestBuilder时自动把该默认的RequestBuilder合并到perform的RequestBuilder中; |
|
|
setGlobalResultMatchers |
设置全局的预期结果验证规则,如我们通过MockMvc测试多个控制器时,假设它们都想验证某个规则时,就可以使用这个 |
|
|
setGlobalResultHandlers |
设置全局的ResultHandler结果处理器 |
|
MockMvcResultMatchers |
静态工厂方法方便操作;具体的API如下 |
|
: |
|
HandlerResultMatchers handler() |
:请求的Handler验证器,比如验证处理器类型/方法名;此处的Handler其实就是处理请求的控制器 |
; |
|
RequestResultMatchers request() |
:得到RequestResultMatchers验证器 |
; |
|
ModelResultMatchers model() |
:得到模型验证器 |
; |
|
ViewResultMatchers view() |
:得到视图验证器 |
|
|
FlashAttributeResultMatchers flash() |
:得到Flash属性验证 |
; |
|
StatusResultMatchers status() |
:得到响应状态验证器 |
; |
|
HeaderResultMatchers header() |
:得到响应Header验证器 |
; |
|
CookieResultMatchers cookie() |
:得到响应Cookie验证器 |
; |
|
ContentResultMatchers content() |
:得到响应内容验证器 |
; |
|
JsonPathResultMatchers jsonPath(String expression, Object ... args)/ResultMatcher jsonPath(String expression, Matcher |
:得到Json表达式验证器 |
; |
|
XpathResultMatchers xpath(String expression, Object... args)/XpathResultMatchers xpath(String expression, Map |
:得到Xpath表达式验证器 |
; |
|
ResultMatcher forwardedUrl(final String expectedUrl) |
:验证处理完请求后转发的url(绝对匹配) |
; |
|
ResultMatcher forwardedUrlPattern(final String urlPattern) |
:验证处理完请求后转发的url(Ant风格模式匹配,@since spring4) |
; |
|
ResultMatcher redirectedUrl(final String expectedUrl) |
:验证处理完请求后重定向的url(绝对匹配) |
; |
|
ResultMatcher redirectedUrlPattern(final String expectedUrl) |
:验证处理完请求后重定向的url(Ant风格模式匹配,@since spring4) |
; |
ResultHandler/MockMvcResultHandlers |
ResultHandler用于对处理的结果进行相应处理的,比如输出整个请求/响应等信息方便调试,Spring mvc测试框架提供了MockMvcResultHandlers静态工厂方法,该工厂提供了ResultHandler print()返回一个输出MvcResult详细信息到控制台的ResultHandler实现 |
|
。 |
MvcResult |
即执行完控制器后得到的整个结果,并不仅仅是返回值,其包含了测试时需要的所有信息,如 |
|
: |
|
MockHttpServletRequest getRequest() |
:得到执行的请求 |
; |
|
MockHttpServletResponse getResponse() |
:得到执行后的响应 |
; |
|
Object getHandler() |
:得到执行的处理器,一般就是控制器 |
; |
|
HandlerInterceptor[] getInterceptors() |
:得到对处理器进行拦截的拦截器 |
; |
|
ModelAndView getModelAndView() |
:得到执行后的ModelAndView |
; |
|
Exception getResolvedException() |
:得到HandlerExceptionResolver解析后的异常 |
; |
|
FlashMap getFlashMap() |
:得到FlashMap |
; |
|
Object getAsyncResult()/Object getAsyncResult(long timeout) |
:得到异步执行的结果 |
; |
测试示例 |
测试普通控制器Java代码 |
mockMvc.perform(get("/user/{id}", 1)) |
执行get请求 |
|
|
.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到控制台 |
|
|
Assert.assertNull(result.getModelAndView()); |
//找不到控制器,404测试 |
|
|
mockMvc.perform(post("/user").param("name", "zhang")) |
//执行传递参数的POST请求(也可以post("/user?name=zhang")) |
|
|
.andExpect(handler().handlerType(UserController.class)) |
//验证执行的控制器类型 |
|
|
.andExpect(handler().methodName("create")) |
//验证执行的控制器方法名 |
|
|
.andExpect(model().hasNoErrors()) |
//验证页面没有错误 |
|
|
.andExpect(flash().attributeExists("success")) |
//验证存在flash属性 |
|
|
.andExpect(view().name("redirect:/user")); |
//验证视图 |
|
|
.andExpect(model().hasErrors()) |
//验证模型有错误 |
|
|
.andExpect(model().attributeDoesNotExist("name")) |
//验证存在错误的属性 |
|
|
.andExpect(view().name("showCreateForm")); |
//验证视图 |
byte[] bytes = new byte[] {1, 2}; |
文件上传 |
|
|
|
|
mockMvc.perform(fileUpload("/user/{id}/icon", 1L).file("icon", bytes)) |
//执行文件上传 |
|
|
.andExpect(model().attribute("icon", bytes)) |
//验证属性相等性 |
|
|
.andExpect(view().name("success")); |
//验证视图 |