LocationRepositoryImpl implements LocationRepository { @Override public Location removeLocation(long id) { Optional<LocationEntity> maybeLocation = repository.findById(id); maybeLocation.ifPresent(locationEntity -> repository.deleteById(id)); LocationEntity locationEntity = maybeLocation.orElseThrow( () -> new IllegalArgumentException("Location{id=" + id + "} doesn't exist")); Location location = toDomain(locationEntity); logger.info("Deleted location {}.", location.fullDescription()); return location; } @Autowired  LocationRepositoryImpl(LocationCrudRepository repository); @Override Location createLocation(Coordinates coordinates, String description); @Override List<Location> locations(); @Override Location removeLocation(long id); @Override void removeAll(); @Override Optional<Location> find(long locationId);  }
@Test void remove_created_location_by_id() { LocationEntity locationEntity = locationEntity(testLocation); final long id = testLocation.id(); when(crudRepository.findById(id)).thenReturn(Optional.of(locationEntity)); Location removed = repository.removeLocation(id); assertThat(removed).isEqualTo(testLocation); verify(crudRepository).deleteById(id); }
@Test void removing_nonexistent_location_should_fail() { when(crudRepository.findById(anyLong())).thenReturn(Optional.empty()); int uniqueNonexistentId = 7173; assertThatIllegalArgumentException() .isThrownBy(() -> repository.removeLocation(uniqueNonexistentId)) .withMessageContaining(String.valueOf(uniqueNonexistentId)); }