3

我正在尝试Resilience4j CircuitBreaker对我的服务的配置进行单元测试。但是我在 throw 时无法调用回退方法HttpServerErrorException。但是,我尝试mock调用不会使用回退方法的对象。

后备工作正常。失败时AService,调用将定向到回退方法调用BService。如何编写测试用例来验证它们?

我是 Resilience4j 和回退模式的新手。请帮我测试一下。

服务等级

@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();
    }
}

服务测试

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


    }
}
4

0 回答 0