Any samples to unit test fallback using Hystrix Spring Cloud

会有一股神秘感。 提交于 2019-12-07 03:10:05

问题


I wish to test the following scenarios:

  1. Set the hystrix.command.default.execution.isolation.thread.timeoutInMillisecond value to a low value, and see how my application behaves.
  2. Check my fallback method is called using Unit test.

Please can someone provide me with link to samples.


回答1:


A real usage can be found bellow. The key to enable Hystrix in the test class are these two annotations: @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
        }
    }



回答2:


Fore open the circuit in your unit test case just before you call the client. Make sure fall back is called. You can have a constant returned from fallback or add some log statements. Reset the circuit.

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

}


来源:https://stackoverflow.com/questions/29039360/any-samples-to-unit-test-fallback-using-hystrix-spring-cloud

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!