Spring / Resilience4j Interview questions
How do you write a unit test for a CircuitBreaker-protected method?
Build the CircuitBreaker from an explicit, test-specific CircuitBreakerConfig rather than relying on the application's real application.yml values, so the test controls thresholds directly instead of depending on production configuration that might change independently.
CircuitBreakerConfig config = CircuitBreakerConfig.custom() .slidingWindowSize(4) .minimumNumberOfCalls(4) .failureRateThreshold(50) .waitDurationInOpenState(Duration.ofMillis(100)) .build(); CircuitBreaker cb = CircuitBreaker.of("test", config); Supplier<String> decorated = CircuitBreaker.decorateSupplier(cb, () -> { throw new RuntimeException(); }); for (int i = 0; i < 4; i++) { Try.ofSupplier(decorated); } assertEquals(CircuitBreaker.State.OPEN, cb.getState());
For fallback logic specifically, it's often simpler to skip waiting for real failures and directly call cb.transitionToOpenState(), then verify the decorated call rejects with CallNotPermittedException and that the fallback handler produces the expected result.
More Related questions...