Linked Questions

Popular Questions

How to test injected mock with try-catch

Asked by At

I'm doing simple unit test by using mockMvc with springboot. is origin source code and is test source code. There are 3 mocks injected to SampleCtrl and they are working well except SampleService class. As you can see, SampleService wrapped with try-catch block. So, I have no idea how to call the method in mock class to get return or throw exception in test source code.

I removed try-catch block in origin code, also given() method in test code. It worked well. That's why I think the try-catch block is undoubted reason to make error.

@PostMapping(path = "/save", consumes = "application/json")
public ResponseEntity<Map<String, Object>> setEmp(@RequestBody 
List<EmpSaveVo> vos) {

    try {
        msg = service.setEmp(vos);
    } catch (Exception e) {
        msg = e.getMessage();
    result = messageTrans.getMapLang(msg);

    return messageReturn.getRestResp(result, msg);

private MockMvc mockMvc;

private SampleService service;

private MessageTrans messageTrans;

private MessageReturn messageReturn;

private SampleCtrl sampleCtrl;

public void setup() {
    mockMvc = MockMvcBuilders.standaloneSetup(sampleCtrl).build();

public void givenEmployeeDataWhenPostEmpSave() throws Exception {
    List<EmpSaveVo> empSaveVos = new ArrayList<>();
    EmpSaveVo empSaveVo = new EmpSaveVo();
    empSaveVo.set_status((long) Status.Modified.getStatus());

    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(messageReturn.getRestResp(any(), anyString()))
    .willReturn(new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK));


Consequently, I want to see this console log.

           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 = []

Related Questions