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