繁体   English   中英

如何处理客户端服务中未找到的状态

[英]How to handle Status NOT FOUND in client service

我是开发微服务应用程序后端的新手。

我正在尝试从 Spring Boot 微服务架构中的其他服务中获取国家/地区详细信息。 作为单元测试的一部分,我正在编写一个负面测试用例,其中我请求的 CommonData 微服务在传递不存在的国家/地区代码时将返回未找到的 http 状态。

然而 ResponseEntity 正在抛出一个 HttpClientErrorExeption$NotFound: 404: [no body]。

我应该如何处理这种预期的反应?

CommonData 微服务 - 控制器

@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);
    }
}

用户微服务 - 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();
}

负面测试案例

@Test
void shouldReturnNullWhenInvalidCountryCodePassed() throws Exception {
    String countryCode = "GEN";
    Country actual = commonDataService.getCountryByCode(countryCode);
    assertNull(actual);
}

也欢迎任何改进代码的建议。

尝试使用 Junit 的 assertThrows

@ResponseStatus(code = HttpStatus.NOT_FOUND) 公共类 NotFoundException extends RuntimeException {}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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