I am trying to Unit test the Resilience4j CircuitBreaker configuration for my service. But I am unable to call the fallback method when I throw HttpServerErrorException. However I try to mock the objects the call is not going to the fallback method.
The fallback works fine. When AService fails, the call is directed to fallback method calling BService. How do I write test cases to verify them?
I am new to Resilience4j and fallback patterns. Please help me to test this.
Service class
@AllArgsConstructor
@Service
public class ServiceImpl implements Service {
@NonNull
private AService aService;
@NonNull
private BService bService;
@CircuitBreaker(name = "resilienceConfig", fallbackMethod = "fallback")
@TimeLimiter(name = "resilienceConfig")
@Override
public Mono<List<PojoClass>> method(Mono<PojoClass2> pc) {
return pc
.map(PojoClass2::getPojoClass2)
.flatMapMany(Flux::fromIterable)
.map(Pojo3::getId)
.flatMap(service -> aService.method(param1, param2))
.flatMapMany(Flux::fromIterable)
.map(this::changeValues)
.collectList();
}
public Mono<List<PojoClass>> fallback(Mono<PojoClass2> pc, Throwable ex) {
return pc
.map(PojoClass2::getPojoClass2)
.flatMapMany(Flux::fromIterable)
.map(Pojo3::getId)
.flatMap(service -> bService.method(param1, param2))
.flatMapMany(Flux::fromIterable)
.map(this::changeValues)
.collectList();
}
}
ServiceTest
@SpringBootTest(classes = Application.class)
@RunWith(MockitoJUnitRunner.class)
public class ServiceImplTest {
@Mock
private AService aService;
@Mock
private BService bService;
@InjectMocks
ServiceImpl serviceImpl;
@Test
public void enrichException() {
doThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR))
.when(aService)
.method(param1, param2);
Mono<List<PojoClass>> pojo = serviceImpl.method(param1);
}
}