简体   繁体   中英

How to handle Status NOT FOUND in client service

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 {}

assertThrows(NotFoundException.class, ()->{objectName.yourMethod("not found")}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM