记录一下最近在写单元测试遇到的各种传参的形式,一般简单的传参形式请见 传送门
Springboot 单元测试简单介绍和启动所有测试类的方法
这篇记录一些较为复杂的传参形式啥也不说先上一波controller 层的代码
@RequestMapping("/task")
@RestController
@SuppressWarnings("all")
public class TaskController {
private static final Logger LOG = LoggerFactory.getLogger(TaskController.class);
@Autowired
private AssessmentInfoService assessmentInfoService;
@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 = assessmentInfoService.getTaskInfoByEmployeeId(map);
List<TaskInfo> list = taskInfoByEmployeeId.getList();
map.put("recordsTotal", taskInfoByEmployeeId.getTotal());
map.put("data", list);
return R.ok(map);
}
/**
* 获取任务详情
*
* @param taskId
* @return
*/
@ApiOperation(value = "获取任务详情")
@PostMapping("/getTaskInfo")
public R getTaskInfo(Integer taskId) {
return R.ok(assessmentInfoService.getTaskInfo(taskId));
}
@ApiOperation(value = "获取考评记录")
@GetMapping("/getAssessmentInfo")
public R getAssessmentInfo(Integer assessmentId) {
if(assessmentId != null){
return assessmentInfoService.getAssessmentInfo(assessmentId);
}else {
return R.error(ErrorCode.PARAM_ERROR.getValue(), ErrorCode.PARAM_ERROR.getMessage());
}
}
/**
* 获取分发详情
*
* @param map
* @return
*/
@ApiOperation(value = "普通用户获取分发详情")
@PostMapping("/getAssessmentInfoByEmployeeId")
public R getAssessmentInfoByEmployeeId(@RequestBody Map<String, Object> map) {
Map<String, String> stringMap = assessmentInfoService.countAssessmented(map);
PageInfo<AssessmentDto> assessmentInfoByEmployeeId = assessmentInfoService.getAssessmentInfoByEmployeeId(map);
List<AssessmentDto> list = assessmentInfoByEmployeeId.getList();
map.put("recordsTotal", assessmentInfoByEmployeeId.getTotal());
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 = distributeVo.getAssessmentIds();
List<PersonnelInfo> personnelInfos = distributeVo.getPersonnelInfos();
personnelInfos.forEach(s -> s.setId(null));
List<Role> roles = SessionUtil.getUser(request).getRoles();if (roles != null) {
if (roles.toString().contains("id=4") || roles.toString().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) {
return taskService.createTask(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
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 = request.getSession();
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())
.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 = JSONObject.toJSONString(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 = JSONObject.toJSONString(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 = JSONObject.toJSONString(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 = JSONObject.toJSONString(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", requestJson.getBytes());
两个MockMultipartFile对象 第一个参数是controller 对应的value值 是文件名(实体第二个可以为空) 第三个是格式 application/json 代表是json格式就是传入的实体
最后是输入形式 文件输入流
* @throws Exception
*/
@Test
public void createTask() throws Exception {
TaskInfo taskInfo = new TaskInfo();
taskInfo.setCreaterId("674470");
String requestJson = JSONObject.toJSONString(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", requestJson.getBytes());
MvcResult mvcResult =
mockMvc.perform(MockMvcRequestBuilders.multipart("/task/createTask").file(mfile).file(jsonFile).session(session))
.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print())
.andReturn();
}
}
各个的讲解都以在方法上注释 有问题欢迎评论 ,写的有问题可以指出 ,共同成长;