An example of a REST service whose task is to receive and save/update geolocation information from mobile devices.
Follow the technologies and solutions present in this project below:
- Spring Boot 2
- Maven
- Databases using Postgres on Docker
- Spring Data JPA
- Validation of a user input
- Unit Testing
- Testing the GeolocationRepository class using the settings with
@DataJpaTest
@Test
void selectExistsDeviceId_deviceIdExists_returnTrue() {
//given
String deviceId = "12345";
Geolocation geolocation = new Geolocation(deviceId, 505430, 1423412);
underTest.save(geolocation);
//when
boolean expected = underTest.selectExistsDeviceId(deviceId);
//then
assertThat(expected).isTrue();
}
@Test
void selectExistsDeviceId_deviceIdNotExist_returnFalse() {
//given
String deviceId = "12345";
//when
boolean expected = underTest.selectExistsDeviceId(deviceId);
//then
assertThat(expected).isFalse();
}
- GeolocationService class test examples using
@Mock
and@Captor
.
@Test
void addGeolocation_deviceIdNotExist_geolocationSaved() {
//given
Geolocation geolocation = new Geolocation("12345", 505430, 1423412);
//when
underTest.addGeolocation(geolocation);
//then
then(geolocationRepository).should().save(geolocationArgumentCaptor.capture());
Geolocation geolocationArgumentCaptorValue = geolocationArgumentCaptor.getValue();
assertThat(geolocationArgumentCaptorValue).isEqualTo(geolocation);
}
@Test
void getAllGeolocations_emptyList_thrownNotFoundException() {
//given
given(geolocationRepository.findAll()).willReturn(Collections.emptyList());
// when / then
assertThatThrownBy(() -> underTest.getAllGeolocations())
.isInstanceOf(NotFoundException.class)
.hasMessage("The geolocation list is empty");
}