大家好,欢迎来到IT知识分享网。
使用MockMvc有两种方式
- 指定孤立的某个controller进行测试:单元测试,不需要构造ApplicationContext
- 集成整个WebApplicationContext进行测试:集成测试,会构造整个WebAppApplicationContext
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(xxx)
class MyWebTests {
MockMvc mockMvc;
@BeforeEach
void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(new AccountController()).build();
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(xxx)
@WebAppConfiguration
class MyWebTests {
MockMvc mockMvc;
@Autowired
public WebApplicationContext wac;
@BeforeEach
void setup(WebApplicationContext wac) {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
}
假如使用孤立的某个controller
1. 在单元测试的启动过程中,可以看到如下日志,StandaloneMockMvcBuilder仅为这个controller创建RequestMapping和具体方法的映射。
2.可以为该孤立的controller创建一些特性,比如声明header中的accept属性,或返回的response中,状态码为200,contentType为application/json;charset=UTF-8
MockMvc mockMvc = standaloneSetup(new MusicController())
.defaultRequest(get("/").accept(MediaType.APPLICATION_JSON))
.alwaysExpect(status().isOk())
.alwaysExpect(content().contentType("application/json;charset=UTF-8"))
.build();
常用的静态类
-
MockMvcBuilders.*
-
MockMvcRequestBuilders.*
-
MockMvcResultMatchers.*
-
MockMvcResultHandlers.*
Post请求
json形式post
mockMvc.perform(post("/user") // 路径
.contentType(MediaType.APPLICATION_JSON) //用contentType表示具体请求中的媒体类型信息,MediaType.APPLICATION_JSON json数据格式
.content(example) // 入参中的对象
.accept(MediaType.APPLICATION_JSON)) //accept指定客户端能够接收的内容类型
.andExpect(content().contentType("application/json;charset=UTF-8")) //验证响应contentType == application/json;charset=UTF-8
.andExpect(jsonPath("$.id").value(1)) //验证id是否为1,jsonPath的使用
.andExpect(jsonPath("$.name).value("onion"); // 验证name是否等于onion
文件形式post
mockMvc.perform(multipart("/doc").file("a1", "ABC".getBytes("UTF-8")));
Get请求
mockMvc.perform(get("/hotels?thing={thing}", "somewhere")); // 改写url后缀形式传参
或
mockMvc.perform(get("/hotels").param("thing", "somewhere")); // httpServletRequest中的param传参
打印请求的出入参
MockMvcResultHandler的print()方法能够打印出出入参
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/vendor/batchModifyMerge").content(data)
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.ALL)).
andDo(MockMvcResultHandlers.print()).andReturn();
// 打印结果如下
MockHttpServletRequest:
HTTP Method = POST
Request URI = /vendor/batchModifyMerge
Parameters = {}
Headers = {Content-Type=[application/json], Accept=[*/*]}
Handler:
Type = com.vip.ps.controller.VisApplyHeadController
Method = public MyController.batchModifyMerge(java.util.List<Object>,javax.servlet.http.HttpServletRequest)
Async:
Was async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"status":"error","data":{},"message":"会话失效"}
Forwarded URL = null
Redirected URL = null
Cookies = []
往请求前面增加filter
mockMvc = standaloneSetup(new PersonController()).addFilters(new CharacterEncodingFilter()).build();
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/15468.html