springboot-Controller单元测试各种传参测试单个⽂件上传,单个实体类上传。。。记录⼀下最近在写单元测试遇到的各种传参的形式,⼀般简单的传参形式请见传送门
这篇记录⼀些较为复杂的传参形式啥也不说先上⼀波controller 层的代码
@RequestMapping("/task")
@RestController
@SuppressWarnings("all")
public class TaskController {
private static final Logger LOG = Logger(TaskController.class);
@Autowired
private AssessmentInfoService assessmentInfoService;
springboot是啥
@Autowired
private EvaTaskService taskService;
@Autowired
private SendEmailService sendEmailService;
@Autowired
private UserService userService;
/**
* ⾮管理员查看任务列表
*
* @param map
* @return
*/
@ApiOperation(value = "普通⽤户查看任务列表分页")
@PostMapping("/getTaskInfoByEmployeeId")
public R getTaskInfoByEmployeeId(@RequestBody Map<String, Object> map) {
PageInfo<TaskInfo> taskInfoByEmployeeId = TaskInfoByEmployeeId(map);
List<TaskInfo> list = List();
map.put("recordsTotal", Total());
map.put("data", list);
return R.ok(map);
}
/**
* 获取任务详情
*
* @param taskId
* @return
*/
@ApiOperation(value = "获取任务详情")
@PostMapping("/getTaskInfo")
public R getTaskInfo(Integer taskId) {
return R.TaskInfo(taskId));
}
@ApiOperation(value = "获取考评记录")
@GetMapping("/getAssessmentInfo")
public R getAssessmentInfo(Integer assessmentId) {
if(assessmentId != null){
AssessmentInfo(assessmentId);
}else {
(ErrorCode.Value(), ErrorCode.Message());
}
}
/**
* 获取分发详情
*
* @param map
* @return
*/
@ApiOperation(value = "普通⽤户获取分发详情")
@PostMapping("/getAssessmentInfoByEmployeeId")
public R getAssessmentInfoByEmployeeId(@RequestBody Map<String, Object> map) {
Map<String, String> stringMap = untAssessmented(map);
PageInfo<AssessmentDto> assessmentInfoByEmployeeId = AssessmentInfoByEmployeeId(map);
List<AssessmentDto> list = List();
map.put("recordsTotal", Total());
map.put("data", list);
map.put("number", stringMap);
return R.ok(map);
}
/**
* ⼈员考评
*
* @param assessmentInfo
* @return
*/
@ApiOperation(value = "普通⽤户进⾏⼈员考评")
@PostMapping("/updateAssessmentInfo")
public R updateAssessmentInfo(@RequestBody AssessmentInfo assessmentInfo, HttpServletRequest request) {
return assessmentInfoService.updateAssessmentInfo(assessmentInfo, request);
}
/**
* 普通⽤户考评分发
*
* @param employeeId
* @param assessmentIds
* @param personnelInfos
* @return
*/
@ApiOperation(value = "普通⽤户考评分发")
@PostMapping("/distributeTask")
public R distributeTask(@RequestParam(value = "employeeId") String employeeId, @RequestParam(value = "assessmentIds") List<Integer> assessmentIds,                            @RequestBody List<PersonnelInfo> personnelInfos, HttpServletRequest request) {
return assessmentInfoService.distributeTask(employeeId, assessmentIds, personnelInfos, request);
}
@ApiOperation(value = "管理员分发")
@PostMapping("/adminDistributeTask")
public R adminDistributeTask(@RequestParam("assessmentIds") List<Integer> assessmentIds, @RequestBody List<PersonnelInfo> personnelInfos,                                HttpServletRequest request) {
return assessmentInfoService.adminDistributeTask(assessmentIds, personnelInfos, request);
}
@ApiOperation(value = "考评分发")
@PostMapping("/distribute")
public R distribute(@RequestParam(value = "employeeId") String employeeId, @RequestBody DistributeVo distributeVo, HttpServletRequest request) throws IOException, IamException {
List<Integer> assessmentIds = AssessmentIds();
List<PersonnelInfo> personnelInfos = PersonnelInfos();
personnelInfos.forEach(s -> s.setId(null));
List<Role> roles = User(request).getRoles();if (roles != null) {
if (String().contains("id=4") || String().contains("id=1")) {
return assessmentInfoService.adminDistributeTask(assessmentIds, personnelInfos, request);
} else {
return assessmentInfoService.distributeTask(employeeId, assessmentIds, personnelInfos, request);
}
} else {
return assessmentInfoService.distributeTask(employeeId, assessmentIds, personnelInfos, request);
}
}
@PostMapping("/createTask")
@ApiOperation("创建考评任务")
@SystemControllerLog(title = "创建考评任务", businessType = BusinessType.INSERT)
public R createTask(@Valid @RequestPart TaskInfo info, @RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) { ateTask(info, request, file);
}
}
对应的各个⽅法单元测试⼤家对⽐看⼀下 TaskControllerTest
SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@SuppressWarnings("all")
public class TaskControllerTest {
@Autowired
private WebApplicationContext wac;
@Autowired
private MockMvc mockMvc;
private MockHttpSession session;
@Autowired
@Autowired
HttpServletRequest request;
/**
* 模拟登录
*/
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
session = new MockHttpSession();
User user = new User();
user.setName("李光明");
user.setEmployeeId("674470");
Role role = new Role();
role.setId(1);
List<Role> roleList = new ArrayList<>();
roleList.add(role);
user.setRoles(roleList);
user.setEmployeeId("674470");
session.setAttribute("user", user);
HttpSession session = Session();
session.setAttribute("user", user);
}
/**
* 模拟Map 形式的传参
* session(session) ---是传⼊session信息
* @throws Exception
*/
@Test
public void getTaskInfoByEmployeeId() throws Exception {
MultiValueMap<String, String> param = new LinkedMultiValueMap<String, String>();
param.add("offset", "1");
param.add("limit", "10");
param.add("taskName", "");
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/task/getTaskInfoByEmployeeId").params(param)                .accept(MediaType.APPLICATION_JSON).session(session)).andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print()).andReturn();
}
/**
* 这个就是⼀般的传参很简单 key value形式
* @throws Exception
*/
@Test
public void getTaskInfo() throws Exception {
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/task/getTaskInfo").param("taskId", "1")
.accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print()).andReturn();
}
@Test
public void getAssessmentInfo() throws Exception {
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.post("/task/getAssessmentInfo").param("assessmentId", "1")
.accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print()).andReturn();
}
/**
* 这种也可以使⽤在⼀个实体类传参@RequestBody 对应字段也⾏但是⼀般不是这么写下⾯有具体的⽅法
* @throws Exception
*/
@Test
public void getAssessmentInfoByEmployeeId() throws Exception {
MultiValueMap<String, String> param = new LinkedMultiValueMap<String, String>();
param.add("offset", "1");
param.add("limit", "10");
param.add("employeeId", "674470");
param.add("position", null);
param.add("assessmentCondition", null);
param.add("name", null);
param.add("level", null);
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.post("/task/getAssessmentInfoByEmployeeId").params(param)
.accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
.accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print()).andReturn();
}
@Test
public void updateAssessmentInfo() throws Exception {
MultiValueMap<String, String> param = new LinkedMultiValueMap<String, String>();
param.add("assessmentId", "1");
param.add("comment", "55");
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.post("/task/getTaskInfo").params(param).accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn();
}
/**
* 这个就是实体传参@RequestBody 这个是List<PersonnelInfo>形式单个也是⼀样
* 转换成json格式 String requestJson = JSONString(personnelInfos);
* .contentType(MediaType.APPLICATION_JSON).param("assessmentId", "1").param("employee", "674470")
.content(requestJson) 使⽤content传送参数
* @throws Exception
*/
@Test
public void distributeTask() throws Exception {
List<PersonnelInfo> personnelInfos = new ArrayList<>();
personnelInfos.add(new PersonnelInfo());
String requestJson = JSONString(personnelInfos);
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/task/getAssessmentInfoByEmployeeId")
.contentType(MediaType.APPLICATION_JSON).param("assessmentId", "1").param("employee", "674470")
.content(requestJson).session(session)).andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print()).andReturn();
}
/**
* ⼀般param 只能是key value 两个都是String类型想传⼊List<Integer/String>
*    param("assessmentIds", "1,2")都可以使⽤这种形式会⾃动识别传⼊的类型
* @throws Exception
*/
@Test
public void adminDistributeTask() throws Exception {
List<PersonnelInfo> personnelInfos = new ArrayList<>();
personnelInfos.add(new PersonnelInfo());
String requestJson = JSONString(personnelInfos);
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.post("/task/adminDistributeTask").contentType(MediaType.APPLICATION_JSON)
.param("assessmentIds", "1,2    ").content(requestJson).session(session).accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn();
}
@Test
public void distribute() throws Exception {
DistributeVo distributeVo = new DistributeVo();
List<Integer> assessmentIds = new ArrayList<>();
assessmentIds.add(1);
PersonnelInfo personnelInfo = new PersonnelInfo();
personnelInfo.setDistributorId("65422");
List<PersonnelInfo> personnelInfos = new ArrayList<>();
personnelInfos.add(personnelInfo);
distributeVo.setAssessmentIds(assessmentIds);
distributeVo.setPersonnelInfos(personnelInfos);
String requestJson = JSONString(distributeVo);
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.post("/task/distribute").contentType(MediaType.APPLICATION_JSON)
.
param("employeeId", "674470").content(requestJson).session(session).accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn();
}
/**
* 重点来了⽂件(file)和实体(info)的 @RequestPart
* 关键代码
*  MockMultipartFile mfile = new MockMultipartFile("file", "外包⼈员花名册.xls", "xls", new FileInputStream(file));
MockMultipartFile jsonFile = new MockMultipartFile("info", "", "application/json", Bytes());
两个MockMultipartFile对象第⼀个参数是controller 对应的value值是⽂件名(实体第⼆个可以为空)第三个是格式 application/json 代表是json格式就是传⼊的实体最后是输⼊形式⽂件输⼊流
* @throws Exception
* @throws Exception
*/
@Test
public void createTask() throws Exception {
TaskInfo taskInfo = new TaskInfo();
taskInfo.setCreaterId("674470");
String requestJson = JSONString(taskInfo);
File file=new File("C:/Users/itw0002/Downloads/外包⼈员花名册.xls");
MockMultipartFile mfile = new MockMultipartFile("file", "外包⼈员花名册.xls", "xls", new FileInputStream(file));
MockMultipartFile jsonFile = new MockMultipartFile("info", "", "application/json", Bytes());
MvcResult mvcResult =
mockMvc.perform(MockMvcRequestBuilders.multipart("/task/createTask").file(mfile).file(jsonFile).session(session))                        .andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print())
.andReturn();
}
}
各个的讲解都以在⽅法上注释有问题欢迎评论,写的有问题可以指出,共同成长;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。