使用Hystrix Spring Cloud进行回退单元测试的示例有哪些?

6

我希望测试以下情况:

  1. hystrix.command.default.execution.isolation.thread.timeoutInMillisecond的值设置为较低值,并查看我的应用程序的表现。
  2. 使用单元测试检查我的备选方法是否被调用。

请有人向我提供示例链接。


@Spencergibb,请问你能帮忙吗? - Jerry
2个回答

8
下面是一个真实的使用示例。在测试类中启用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
        }
    }

1
优秀的答案,帮我省去了很多工作和挫折。 - Working Title

1
在调用客户端之前,在您的单元测试用例中打开电路。确保调用回退。您可以从回退中返回一个常量或添加一些日志语句。 重置电路。
@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");

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接