How to mock a exception in rest controller where the exception is thrown from a service

Viewed 1265

I am working on writing a test cases for rest Controller in Spring boot.

To give some context about the problem, I am not able to mock the exception that has been thrown from service at the controller layer.

I am using PowerMokito for writing test cases.

@RunWith(PowerMockRunner.class)
@PrepareForTest(UserApiController.class)
public class UserApiControllerTest {


   /* private MockMvc mockMvc;*/
    @Mock
    GenericService genericService;

    @Mock
    UserService userService;

    @Mock
    UserRoleService userRoleService;

    @Mock
    MessageService messageService;

    @Mock
    CurrentUserService currentUserService;

    @Mock
    UserRepository userRepository;

    @Mock
    UserRoleRepository userRoleRepository;

    @InjectMocks
    UserApiController userApiController;


    @Before
    public void setup() {
        // this must be called for the @Mock annotations above to be processed
        MockitoAnnotations.initMocks(this);
        //Set up mocking for repository methods
    }

    @Test(expected = DuplicateUserEmailException.class)
    public void saveUserByEmailFailure() throws Exception {
        HashMap mockUser = new HashMap<String,Object>();
        mockUser.put("email","test_dy1@gmail.com");
        String user = new ObjectMapper().writeValueAsString(mockUser);
        doThrow(new DuplicateUserEmailException()).
                when(userService).saveUserByEmailId(any());

        userApiController.saveUserByEmailId(user);
    }

Please find the details of the controller below.

    @RequestMapping(value = "/save_user_by_email", method = RequestMethod.POST)
    public String saveUserByEmailId(@RequestParam("user") String user) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        HashMap<String, Object> userJson = new HashMap<String, Object>();
        userJson = mapper.readValue(user, new TypeReference<Map<String, Object>>(){});
        JsonObjectBuilder responseBuilder = Json.createObjectBuilder();
        try {
            userService.saveUserByEmailId(userJson);
            responseBuilder.add("success", true).add("code", genericService.getSuccessCode()).add("message",
                    userJson.containsKey("id") ? messageService.getMessage("message.success.update")
                            : messageService.getMessage("message.success.create"));
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
            if(exception instanceof DuplicateUserEmailException)
                throw new DuplicateUserEmailException();
        }

        return responseBuilder.build().toString();
    }
3 Answers

Finally, I solved it. Please find the code below and comment if you have doubts.

@RunWith(PowerMockRunner.class)
@PrepareForTest(UserApiController.class)
public class UserApiControllerTest {


    private MockMvc mockMvc;
    @Mock
    GenericService genericService;

    @Mock
    UserService userService;

    @Mock
    UserRoleService userRoleService;

    @Mock
    MessageService messageService;

    @Mock
    CurrentUserService currentUserService;

    @InjectMocks
    ApiExceptionHandlerAdvice apiExceptionHandlerAdvice;

    @Mock
    UserRepository userRepository;

    @Mock
    UserRoleRepository userRoleRepository;

    @InjectMocks
    UserApiController userApiController;


    @Before
    public void setup(){

      //  MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(userApiController).setControllerAdvice(apiExceptionHandlerAdvice).build();
    }

    @Test
    public void testAddDuplicateCustomer() throws Exception {

        HashMap mockUser = new HashMap<String,Object>();
        mockUser.put("email","test_dy1@gmail.com");
        String user = new ObjectMapper().writeValueAsString(mockUser);
        when(userService.saveUserByEmailId(any())).thenThrow(DuplicateUserEmailException.class);
        when(messageService.getMessage(any())).thenReturn("200");
        RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/user/api/save_user_by_email").param("user",user);
        MvcResult result = mockMvc.perform(requestBuilder).andReturn();
        MockHttpServletResponse response = result.getResponse();
        assertEquals(HttpStatus.BAD_REQUEST.value(), response.getStatus());
        // assertEquals(HttpStatus.BAD_REQUEST.value(), response.getStatus());
    }

Try it like this:

PowerMockito.doThrow(new DuplicateUserEmailException()).
                when(userService).saveUserByEmailId(any(String.class));

Make sure saveUserByEmailId method is void return type

Possible you're not passing that mock instance towards userApiController real instance. That is a really common mistake with mock services. Are you using @InjectMocks for that, or are you constructing userApiController instance manually ? Could you please tell us the annotations that are you using above test class ?

To be honest I'd suggest to use only Mockito since with PowerMock you can mock a lot of crazy things, and it's making byte code manipulation

With Mockito this will look like this:

doThrow(newRuntimeException()).when(paymentService).completePayment(any(), any(), any());

And if you want to mock networking calls, please use WireMock, we've used it for a long time now and it adds a lot of value to our tests pack.

Related