Im单元测试一种服务方法,其中使用(模拟)rest模板向另一个服务发出请求。它具有@HystrixCommand属性,以便在必要时调用后备方法。在测试中,这与我的工作方式相同,这意味着其余模板返回Bad Request时,将调用fallback方法。但是,我尝试进行单元测试,并手动使模拟的其余模板返回Http 400错误请求。我很惊讶地看到这不会触发Hystrix后备。有人知道为什么吗?
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "fallback")
public SomeResponse restCall(SomeRequest request) {
HttpEntity<Object> httpEntityRequest = new HttpEntity<>(request);
ResponseEntity<R> response = restTemplate.exchange(
"http://localhost:5000/otherservice,
HttpMethod.POST,
httpEntityRequest,
responseClass);
if (response != null)
return response.getBody();
else
return new SomeResponse();
}
private SomeResponse fallback(SomeRequest request) {
log.error("Log Error);
return null;
}
我的单元测试:
@Mock
private Appender<ILoggingEvent> mockAppender;
@Captor
private ArgumentCaptor<LoggingEvent> captorLoggingEvent;
@MockBean
private RestTemplate mockRestTemplate;
@Autowired
private SomeService service;
@Before
public void setUp() {
Logger logger = (Logger)
LoggerFactory.getLogger(SomeServiceTest.class);
logger.addAppender(mockAppender);
}
@Test
public void restCallTest() {
ResponseEntity<SomeResponse> response = new ResponseEntity<>(HttpStatus.BAD_REQUEST);
when(mockRestTemplate.exchange(anyString(), any(), any(), eq(BannerResponse.class))).thenReturn(response);
SomeResponse someResponse = service.fallback(new SomeRequest());
verify(mockRestTemplate, times(1)).exchange(anyString(), any(), any(), eq(SomeResponse.class));
verify(mockAppender).doAppend(captorLoggingEvent.capture());
assertThat(captorLoggingEvent.getValue().toString(), containsString("Log error"));
assertNull(someResponse);
}
此致