Wrapper
Wrapper

Reputation: 932

Proper way to test POST service which may throw exception using Mockito?

I have a simple REST service written in Java (Spring Boot). The idea is to allow user to add new entity if that entity doesn't exist. If it does exist I'm throwing an exception.

Here is code:

    public ResponseEntity<String> addReadings(int clientId, int year, int month, double additionalConsumption) throws NoSuchMessageException, IllegalModificationException{     
    
    Optional<Client> clientOptional = clientService.findByClientId(clientId);

    if (clientOptional.isEmpty()) {
        return ResponseEntity.status(HttpStatus.NO_CONTENT)
                             .header("message", messageSource.getMessage("client.error1", null, new Locale("EN")))
                             .build(); 
    }
    
    Optional<Reading> reading = readingService.findByClientAndYearAndMonth(clientOptional.get(), year, month);
    
    if (reading.isPresent()) throw new IllegalModificationException(messageSource.getMessage("consumption.error2", null, new Locale("EN")));
            
    readingService.save(Reading.builder()
                                .client(clientOptional.get())
                                .year(year)
                                .month(month)
                                .consumption(additionalConsumption)
                                .build());
    

    return ResponseEntity
            .status(HttpStatus.OK)
            .body(messageSource.getMessage("sucess", null, new Locale("EN")));
}

The question is how to test throwing of an exception by using Mockito in Spring framework by using the easiest and most clean way?

Upvotes: 0

Views: 271

Answers (1)

erik
erik

Reputation: 253

Mock readingService so that readingService.findByClientAndYearAndMonth returns an Optional that represents some value, i.e. reading.isPresent() is true.

something like:

Client client = ...
ReadingServiceClass readingService = Mockito.mock(ReadingServiceClass.class);
Mockito
  .when(readingService.findByClientAndYearAndMonth(client, 10, 2020))
  .thenReturn(Optional.of(new Reading(...)));
// ... inject readingService into objectToTest 
try {
  objectToTest.addReadings(1, 2020, 10, 1.0d);
  Assert.fail();
}  (catch IllegalModificationException e) {
  // ... assert details of exception
}

Upvotes: 1

Related Questions