一、说明
对于单元测试,网上有很多的例子这里不加赘述,本文主要说明一种,特殊情况,就是传参时包含两个对象,一个是自定义的类,另一个是String[]。
二、具体展示
1.Controller层代码
public Result insertPerson(@RequestBody Person person, String[] id){具体内容略}
2.测试代码
@Test
void insertPersonTest() throws Exception{
Person personNew = new Person();
personNew.setPersonName("张三");
String[] id ={"14397094-b644-4769-b9b1-acefd96e3377"};
MockHttpSession session = new MockHttpSession();
String person= JSONObject.toJSONString(PerosnNew);
MockHttpServletRequestBuilder params1 = MockMvcRequestBuilders.post("/XXX").
contentType(MediaType.APPLICATION_JSON).
session(session).content(person).param("id",id);
MvcResult mvcResult = mockMvc.perform(params1)
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
String contentAsString = mvcResult.getResponse().getContentAsString();
System.out.println(contentAsString);
}
三、爬坑说明
1.@RequestBody是不可缺少的,由于习惯不同,可能有人不添加
2.两个传参需要分开,不能写在一起,例如用list保存