【问题标题】:Hystrix Fallback not executed in unit testHystrix Fallback 未在单元测试中执行
【发布时间】:2019-08-10 22:26:45
【问题描述】:

我实现了一个断路器,当我运行它时它工作正常(这意味着只要 RestTemplate 接收到一个介于 400 和 599 之间的 HTTP 状态代码,就会运行回退方法)。但是,当我尝试对该回退进行单元测试时,通过返回错误请求 (HTTP 400) 不会调用回退方法。这是为什么呢?

类的片段:

class Test {
@Autowired
private RestTemplate restTemplate;

@HystrixCommand(fallbackMethod = "fallback")
public void test() {
    HttpEntity<Object> testRequest = new HttpEntity<>();

    ResponseEntity<String> response = restTemplate.exchange(
            "http://localhost:8080/testurl",
            HttpMethod.POST,
            testRequest,
            String.class);
}

private void fallback() {
    System.out.println("Fallback method called");
}
}

测试类的片段

@MockBean
private RestTemplate mockRestTemplate;

@Autowired
Test test;

@Test
public void testRestTemplateReturning400() {
    ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.BAD_REQUEST);

    when(mockRestTemplate.exchange(anyString(), any(), any(), eq(String.class))).thenReturn(response);

    test.test();

    verify(mockRestTemplate, times(1)).exchange(anyString(), any(), any(), eq(String.class));
}

【问题讨论】:

  • 是的,我看到了那个页面,但它没有解释为什么在应用程序运行并且 RestTemplate 返回 400 时执行回退方法,但在单元测试中却没有。

标签: java unit-testing hystrix


【解决方案1】:

添加

@EnableCircuitBreaker
@EnableAspectJAutoProxy

到您的测试配置

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 2018-09-30
    • 2013-10-09
    • 2021-04-26
    相关资源
    最近更新 更多