I am fairly new to spring boot. I am trying to test this service class if it throws the IllegalArgumentException.class but somehow the exception is not thrown. Help me get what I am missing. This is a section of the service class:
public ResponseEntity<ModelApiResponse> createResponse(Response response)
throws JsonProcessingException, IllegalArgumentException{
try{
myRepository.save(response);
return new ResponseEntity<>(HttpStatus.valueOf(GlobalVariables.RESPONSE_CODE_201));
} catch (IllegalArgumentException ex){
return new ResponseEntity<>(HttpStatus.valueOf(GlobalVariables.RESPONSE_CODE_500));
}
}
I have tried two test methods. The test method (1):
@Test
public void testThatResponseCreationThrowsErrorWhenSavingFails() throws Exception{
Response responseMock = mock(Response.class);
when(abbyResponseRepositoryMock.save(new Response())).thenThrow(IllegalArgumentException.class);
assertThrows(IllegalArgumentException.class, () -> abbyResponseRepositoryMock.save(abbyResponseMock));
}
Test method two:
@Test
public void testThatResponseCreationThrowsErrorWhenSavingFails() throws Exception {
Mockito.when(chatResponseRepositoryMock.save(new Response())).thenThrow(Mockito.mock(IllegalArgumentException.class));
Response response = new Response();
Response.setMessage("This is a unit test response message");
Response.setNxtMessageId("98765");
mockMvc.perform(post("/api/v1/responses/create-response")
.header(HttpHeaders.AUTHORIZATION, "Basic " + "credentials")
.header(GlobalVariables.X_CORRELATION_ID, "123456")
.header(GlobalVariables.X_SOURCE_APP, "source_app")
.header(GlobalVariables.X_USER, "user")
.header(GlobalVariables.X_USER_ROLE, "user")
.content(this.json(response))
.contentType(contentType))
.andExpect(jsonPath("$.header.responseCode", is(500)))
.andExpect(jsonPath("$.header.responseMessage", is("Error saving chat response")))
.andReturn();
}
Also advise on which test method would be suitable. The controller is just a basic controller class that calls the service class to save a chat response. The service class on the other hand calls the repository to save the chat response.
output:
Expected: is <500>
but: was <201>
Kibet Kyle is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.