【问题标题】:How to handle Status NOT FOUND in client service如何处理客户服务中未找到的状态
【发布时间】:2020-10-03 20:38:57
【问题描述】:

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

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

但是 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();
}

NegativeTestCase

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

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

【问题讨论】:

  • @wak786 "/countries"

标签: java spring-boot rest microservices spring-resttemplate


【解决方案1】:

试试 Junit 的 assertThrows

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

assertThrows(NotFoundException.class, ()->{objectName.yourMethod("未找到")}

【讨论】:

  • 这是处理此类情况的标准方法吗?
  • 我的主要目标是检查返回的状态,如果未找到状态则返回 null。我不希望异常流入调用 getCountryByCode(String) 的方法。因此测试应该检查空值,而不是如果抛出异常。
  • Assertions.assertNull(getCountryByCode(String));您可以尝试 assertNull 在测试中检查 null 值
猜你喜欢
  • 1970-01-01
  • 2019-07-08
  • 1970-01-01
  • 1970-01-01
  • 2016-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-18
相关资源
最近更新 更多