I have the following service method:
@Override
public void deleteGreetingById(Integer greetingId) {
try {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:9123/greetings/" + greetingId);
restTemplate.delete(builder.toUriString());
}catch(HttpClientErrorException ex){
if(ex.getStatusCode().equals(HttpStatus.NOT_FOUND))
throw new GreetingNotFoundException("Greeting with id: " + greetingId + " not found.");
}
}
So as you can see I'm calling a second service which manages all the greetings to delete a specific greeting by id. So there is not much logic in this method. What I want to test is that if the rest call throws an HttpClientException with status code 404 the expected GreetingNotFoundExcpetion is thrown.
I tired to define the test with mockito. As the restTemtplate.delete "returns" void, I have to use the "doThrow" Method based on the documentation. So I defined my test like this:
@Test
public void deleteGreetingByIdInvalidId(){
UriComponentsBuilder builder=UriComponentsBuilder.fromHttpUrl("http://localhost:9123/greetings/1");
doThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)).when(restTemplate).delete(builder.toUriString());
greetingsService.deleteGreetingById(1);
}
I thought about doing it kind of this way. First define, that the rest Template execution results in the HttpClientErrorExceptin with 404 and then define to throw the GreetingNotFoundException. I tried to define the GreetingNotFoundException part like
doThrow(new GreetingNotFoundException("Greeting with id: 1 not found.")).when(greetingsService).deleteGreetingById(1);
The problem is, that the greetingService is injected via @InjectMocks. So I get the error, that greetingservice is not a Mock. I just want to execute the real method ( like when using spy ) but I thought is already done when I use @InjectMocks.
I've just started with mockito and atm I am pretty confused an stuck with handling these two void methods. Thanks in advance
Aucun commentaire:
Enregistrer un commentaire