单元测试中不会调用Hystrix FallbackMethod?

问题描述 投票:0回答:2

我开始在我的应用程序上使用 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
2个回答
1
投票

您的后备方法需要与带有HystrixCommand注释的方法具有

相同的签名
,或者具有带有可选
Throwable
参数的相同签名(这里是相关的Javanica文档)。

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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.