refactor the data service for the consistent behavior in case of failure

This commit is contained in:
steam 2020-02-27 13:58:36 +01:00
parent f448776dd4
commit 9ad22501e9
4 changed files with 17 additions and 10 deletions

View File

@ -23,7 +23,7 @@ public class FeaturesController {
@RequestMapping(value = "/features", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public List<Feature> features() {
return dataService.getAllFeatures();
return dataService.getAllFeatures().orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Unable to find any feature"));
}
@RequestMapping(value = "/features/{id}", method = RequestMethod.GET, produces = "application/json")

View File

@ -10,17 +10,17 @@ public interface DataService {
/**
* returned all possible Features as a list
*
* @return list of Features
* @return Optional of list of Feature in case of features can
* be found or empty Optional
*/
List<Feature> getAllFeatures();
Optional<List<Feature>> getAllFeatures();
/**
* returned specific Feature by given id
*
* @param featureId feature id
* @return Optional of Feature in case of the feature can be
* found
* or an empty Optional
* found or an empty Optional
*/
Optional<Feature> getFeature(final String featureId);
@ -29,7 +29,8 @@ public interface DataService {
* returned a picture as a byte[] representation for given feature id
*
* @param featureId feature id
* @return a picture as a byte[]
* @return Optional of byte[] representing a picture or
* empty optional if no picture can be found for given feature id
*/
Optional<byte[]> getPicture(final String featureId);
}

View File

@ -3,15 +3,14 @@ package click.poweronoff.satellite.service;
import click.poweronoff.satellite.domain.Feature;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@Component
public class DataServiceImpl implements DataService {
public List<Feature> getAllFeatures() {
return Collections.emptyList();
public Optional<List<Feature>> getAllFeatures() {
return Optional.empty();
}
@Override

View File

@ -33,7 +33,7 @@ public class FeaturesControllerTest {
@Test
public void getFeaturesShouldReturnDefaultMessage() throws Exception {
when(dataService.getAllFeatures()).thenReturn(List.of(createTestFeature()));
when(dataService.getAllFeatures()).thenReturn(Optional.of(List.of(createTestFeature())));
this.mockMvc.perform(get("/features")).andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
@ -46,6 +46,13 @@ public class FeaturesControllerTest {
);
}
@Test
public void getFeaturesShouldReturnNotFound() throws Exception {
when(dataService.getAllFeatures()).thenReturn(Optional.empty());
this.mockMvc.perform(get("/features"))
.andExpect(status().isNotFound());
}
@Test
public void getFeatureByIdShouldReturnAMessage() throws Exception {
when(dataService.getFeature(anyString())).thenReturn(Optional.of(createTestFeature()));