我正在用mockmvc和springboot进行简单的单元测试。samplectrl.java是源代码,samplectrltest.java是测试源代码。samplectrl中注入了3个mock,除了sampleservice类之外,它们都工作得很好。如您所见,sampleservice用try-catch块 Package 。所以,我不知道如何调用mock类中的方法来获取测试源代码中的返回或抛出异常。
我删除了源代码中的try catch块,也在测试代码中给出了()方法。效果不错。这就是为什么我认为try-catch块无疑是出错的原因。
示例Ctrl.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 = []
暂无答案!
目前还没有任何答案,快来回答吧!