【问题标题】:Hystrix fallbackMethod will not be called in unit test?Hystrix fallbackMethod在单元测试中不会被调用?
【发布时间】:2018-09-30 00:59:18
【问题描述】:

我开始在我的应用程序上使用 Hystrix 来处理来自外部服务的数据。我的代码中的一些要点:

@HystrixCommand(fallbackMethod = "getImagesFallback")
public ImageResultResource getImages(String url) 
{
    ResponseEntity<ResultResource> result = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(getRequestHeaders()), ResultResource.class);
    return result.getBody().getImageResultResource();
}

public ImageResultResource getImagesFallback(String url, Throwable e) 
{
    return new ImageResultResource();
}

在我的单元测试中,我想测试回退情况,例如当外部服务返回 404 Not Found 响应时,所以我模拟我的测试如下:

doThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND))//
            .when(Mockito.spy(new ImageConnector()))//
            .getImages(myMockedURL)

但是当我运行测试时,我上面定义的 fallbackMethod 似乎没有被调用。它直接返回了我为外部服务模拟的 404 Not Found,而我希望 fallbackMethod 应该在这里被捕获,并且不会在这里抛出 404 Not Found。

谁能给我提示在这种情况下如何测试我的 fallbackMethod,或者我在这里的配置有问题吗?非常感谢!

【问题讨论】:

    标签: unit-testing spring-boot resttemplate hystrix


    【解决方案1】:

    您的后备方法需要与带有 HystrixCommand 注释的方法具有相同的签名,或者具有相同的签名并添加了 Throwable。 Here 是相关的 Javanica 文档

    public ImageResultResource getImagesFallback(String url, Throwable e) {
        return new ImageResultResource();
    }
    

    【讨论】:

    • 嗨 Davin,是的,你是对的,我确实更正了我的后备方法的签名,但在单元测试中仍未调用它
    • 你在使用 Spring Boot 吗?如果是这样,您的测试类在类级别需要@SpringBootTest 注解吗?
    • 是的,我在测试的类级别也有注释@SpringBootTest。 :(
    • 你能发布完整的测试吗?
    【解决方案2】:

    Hystrix 自定义后备方法抛出具有 HystrixRuntimeException 实例的异常。 所以,你需要捕获这个异常并使用它的 getMessage 方法来打印它。

    【讨论】:

      猜你喜欢
      • 2017-10-19
      • 2018-07-18
      • 2019-08-10
      • 2014-03-26
      • 1970-01-01
      • 1970-01-01
      • 2019-07-15
      • 2010-11-25
      • 2015-09-05
      相关资源
      最近更新 更多