Any samples to unit test fallback using Hystrix Spring Cloud

Jerry picture Jerry · Mar 13, 2015 · Viewed 9.1k times · Source

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.

Answer

Razvan Juravle picture Razvan Juravle · Aug 22, 2017

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