0

I have a Circuit breaker implemented which works fine when I run it (meaning the fallback method is run whenever the RestTemplate receives an HTTP status code between 400 and 599). However, when I try to unit test this fallback, by returning a Bad Request (HTTP 400) the fallback method is not invoked. Why is this?

Snippet from class:

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");
}
}

Snippet from test class

@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));
}
Bart Boersma
  • 244
  • 2
  • 13
  • Good to refer: https://stackoverflow.com/questions/43453513/how-can-i-unit-test-javanica-hystrixcommand-annotated-methods – Mebin Joe Mar 20 '19 at 09:16
  • Yes I saw that page, but it doesn't explain why the fallback method is executed when the application runs and RestTemplate returns a 400, but in unit tests it does not. – Bart Boersma Mar 20 '19 at 09:35

1 Answers1

0

Add

@EnableCircuitBreaker
@EnableAspectJAutoProxy

to your test configuration

Buben Ivanov
  • 159
  • 3