You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JUnit测试中使用CircuitBreaker时无法捕获Person参数问题

解决JUnit中CircuitBreaker场景下的参数捕获问题

问题根源在于你测试中mock了CircuitBreaker,但未指定它的行为——默认情况下mock对象不会执行传入的lambda逻辑,导致personClient.sendPerson()根本没被调用,自然verify会失败。

解决方案

给mock的CircuitBreaker设置行为,让它执行传入的Supplier参数:

@Test
void savePerson() {
    // 创建person对象
    Person obj = new Person();
    // 设置必要字段...

    // 关键:让mock的CircuitBreaker执行传入的业务逻辑
    when(circuitBreaker.run(any(Supplier.class), any(Function.class)))
        .thenAnswer(invocation -> {
            Supplier<?> supplier = invocation.getArgument(0);
            return supplier.get();
        });

    when(personClient.sendPerson(any(Person.class))).thenReturn(Response.class);

    customerService.save(obj);

    verify(personClient).sendPerson(captor.capture());
    verifyNoMoreInteractions(personClient);

    var testPerson = captor.getValue();
    // 执行你的断言逻辑
}

原理说明

circuitBreaker.run()方法接收两个参数:第一个是要执行的业务逻辑(Supplier类型),第二个是降级处理逻辑(Function类型)。通过thenAnswer获取传入的Supplier并调用其get()方法,就能触发原本包裹在CircuitBreaker里的personClient.sendPerson()调用,这样后续的参数捕获和verify校验就能正常执行了。

内容的提问来源于stack exchange,提问作者user12601540

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 08:02:10