Hystrix后备未在单元测试中执行

时间:2019-03-20 09:14:23

标签: java unit-testing hystrix

我实现了一个断路器,当我运行它时,它运行良好(这意味着只要RestTemplate接收到400到599之间的HTTP状态代码,就运行fallback方法)。但是,当我尝试对该后备进行单元测试时,通过返回错误请求(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));
}

1 个答案:

答案 0 :(得分:0)

添加

@EnableCircuitBreaker
@EnableAspectJAutoProxy

测试配置