記錄一下最近在寫單元測試遇到的各種傳參的形式,一般簡單的傳參形式請見 傳送門
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();
}
}
各個的講解都以在方法上註釋 有問題歡迎評論 ,寫的有問題可以指出 ,共同成長;