我想测试以下场景:
- 将该
hystrix.command.default.execution.isolation.thread.timeoutInMillisecond
值设置为较低的值,然后查看我的应用程序的行为。 - 检查我的后备方法是使用单元测试调用的。
请有人给我提供样品的链接。
一个真正的用法可以在下面找到。在测试类中启用 Hystrix 的关键是这两个注解:@EnableCircuitBreaker @EnableAspectJAutoProxy
class ClipboardService {
@HystrixCommand(fallbackMethod = "getNextClipboardFallback")
public Task getNextClipboard(int numberOfTasks) {
doYourExternalSystemCallHere....
}
public Task getNextClipboardFallback(int numberOfTasks) {
return null;
}
}
@RunWith(SpringRunner.class)
@EnableCircuitBreaker
@EnableAspectJAutoProxy
@TestPropertySource("classpath:test.properties")
@ContextConfiguration(classes = {ClipboardService.class})
public class ClipboardServiceIT {
private MockRestServiceServer mockServer;
@Autowired
private ClipboardService clipboardService;
@Before
public void setUp() {
this.mockServer = MockRestServiceServer.createServer(restTemplate);
}
@Test
public void testGetNextClipboardWithBadRequest() {
mockServer.expect(ExpectedCount.once(), requestTo("https://getDocument.com?task=1")).andExpect(method(HttpMethod.GET))
.andRespond(MockRestResponseCreators.withStatus(HttpStatus.BAD_REQUEST));
Task nextClipboard = clipboardService.getNextClipboard(1);
assertNull(nextClipboard); // this should be answered by your fallBack method
}
}
在你打电话给客户之前,在你的单元测试用例中打开电路。确保调用 fall back。您可以从后备中返回一个常量或添加一些日志语句。重置电路。
@Test
public void testSendOrder_openCircuit() {
String order = null;
ServiceResponse response = null;
order = loadFile("/order.json");
// use this in case of feign hystrix
ConfigurationManager.getConfigInstance()
.setProperty("hystrix.command.default.circuitBreaker.forceOpen", "true");
// use this in case of just hystrix
System.setProperty("hystrix.command.default.circuitBreaker.forceOpen", "true");
response = client.sendOrder(order);
assertThat(response.getResultStatus()).isEqualTo("Fallback");
// DONT forget to reset
ConfigurationManager.getConfigInstance()
.setProperty("hystrix.command.default.circuitBreaker.forceOpen", "false");
// use this in case of just hystrix
System.setProperty("hystrix.command.default.circuitBreaker.forceOpen", "false");
}