我正在通过将MockMvc与springboot一起使用来进行简单的单元测试。 SampleCtrl.java是原始源代码,而SampleCtrlTest.java是测试源代码。向SampleCtrl注入了3个模拟,除了SampleService类之外,它们运行良好。如您所见,SampleService包含try-catch块。因此,我不知道如何在模拟类中调用方法以在测试源代码中获取返回或引发异常。
我删除了源代码中的try-catch块,也删除了测试代码中的给定()方法。运行良好。这就是为什么我认为try-catch块无疑是导致错误的原因。
SampleCtrl.java
@PostMapping(path = "/save", consumes = "application/json")
@ResponseBody
public ResponseEntity<Map<String, Object>> setEmp(@RequestBody
List<EmpSaveVo> vos) {
result.clear();
try {
msg = service.setEmp(vos);
} catch (Exception e) {
msg = e.getMessage();
}
result = messageTrans.getMapLang(msg);
return messageReturn.getRestResp(result, msg);
}
SampleCtrlTest.java
private MockMvc mockMvc;
@Mock
private SampleService service;
@Mock
private MessageTrans messageTrans;
@Mock
private MessageReturn messageReturn;
@InjectMocks
private SampleCtrl sampleCtrl;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(sampleCtrl).build();
}
@Test
public void givenEmployeeDataWhenPostEmpSave() throws Exception {
List<EmpSaveVo> empSaveVos = new ArrayList<>();
EmpSaveVo empSaveVo = new EmpSaveVo();
empSaveVo.setEmployeeId(100L);
empSaveVo.set_status((long) Status.Modified.getStatus());
empSaveVos.add(empSaveVo);
Gson gson = new Gson();
String element = gson.toJson(empSaveVos);
String msg = "Test";
Map<String, Object> result = new HashMap<>();
result.put("message", msg);
given(service.setEmp(empSaveVos)).willThrow(new Exception());
given(messageTrans.getMapLang(msg)).willReturn(result);
given(messageReturn.getRestResp(any(), anyString()))
.willReturn(new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK));
mockMvc.perform(post("/api/emp/save")
.content(element)
.contentType(MediaType.APPLICATION_JSON)).andDo(print())
.andExpect(status().isOk());
}
因此,我想查看此控制台日志。
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"application/json;charset=UTF-8"]
Content type = application/json;charset=UTF-8
Body = {"message":"Test"}
Forwarded URL = null
Redirected URL = null
Cookies = []