I am new to developing microservice application backend.
I am trying to fetch country details from other service in a spring boot microservice architecture. As part of Unit testing I am writing a negative test case where the CommonData mricroservice I am requesting to would return http status NOT FOUND when passing an non-existing country code.
However the ResponseEntity is throwing a HttpClientErrorExeption$NotFound: 404: [no body].
How should I handle such expected responses?
CommonData MicroService - Controller
@RestController
@RequestMapping("countries")
public class CountryController {
CountryService countryService;
@Autowired
CountryController(CountryService countryService) {
this.countryService = countryService;
}
...
...
...
@GetMapping(path = "/{code}", produces = { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public ResponseEntity<Country> getCountry(@Valid @PathVariable String code) {
Country country = countryService.getCountry(code);
if(country == null)
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(country, HttpStatus.FOUND);
}
}
User MicroService - CommonDataService
Country getCountryByCode(String code) throws Exception {
String path = BASE_PATH + "/" + code;
InstanceInfo instance = eurekaClient.getApplication(serviceId)
.getInstances().get(0);
String host = instance.getHostName();
int port = instance.getPort();
URI uri = new URI("http", null, host, port, path, null, null);
RequestEntity<Void> request = RequestEntity.get(uri)
.accept(MediaType.APPLICATION_JSON).build();
ResponseEntity<Country> response = restTemplate.exchange(request, Country.class);
if(response.getStatusCode() != HttpStatus.FOUND)
return null;
return response.getBody();
}
NegativeTestCase
@Test
void shouldReturnNullWhenInvalidCountryCodePassed() throws Exception {
String countryCode = "GEN";
Country actual = commonDataService.getCountryByCode(countryCode);
assertNull(actual);
}
Any suggestions to improve the code is also welcome.
Try assertThrows of Junit
@ResponseStatus(code = HttpStatus.NOT_FOUND) public class NotFoundException extends RuntimeException {}