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

Spock抛出异常后验证异步Mock交互时BlockingVariable超时如何解决

问题根因

出现该问题有两个核心原因:

  1. 交互声明时机晚于异步调用时机:你将serviceC.save的交互声明写在了then块,此时when块的createAccount已经执行完毕、异常已经抛出,而异步任务可能在进入then块之前就已经执行了serviceC.save调用,此时Mock还没注册该交互,对应的result.set(true)逻辑根本不会触发,最终导致BlockingVariable超时。
  2. 若runAsync使用公共线程池,异步任务可能还没完成调度,主线程就已经走到校验步骤,就算增加等待时长也无法解决第一个逻辑问题。

解决方案

方案1:调整测试交互注册时机

将异步调用对应的交互声明提前到given块,保证异步任务执行前交互已经完成注册:

def "createAccount - should throw Exception and save error"() {
    given:
    def result = new BlockingVariable<Boolean>(10)
    // 提前注册serviceC的交互,避免异步调用时匹配不到stub
    1 * serviceC.save(_) >> { result.set(true) }

    when:
    subject.createAccount("userId")

    then:
    1 * serviceB.createUserAccount(_) >> { throw new Exception() }
    thrown(Exception)
    result.get()
    0 * _
}

方案2:注入线程池消除异步时序问题(更稳定)

业务代码硬编码异步执行逻辑会导致测试时序不可控,建议将异步执行器改为可注入依赖,测试时传入同步执行器,完全消除异步带来的不稳定因素:

第一步:修改业务代码注入线程池

public class ServiceAImpl {
    private final ServiceB serviceB;
    private final ServiceC serviceC;
    private final Executor asyncExecutor;

    // 生产环境传入真实异步线程池,测试环境传入同步执行器
    public ServiceAImpl(ServiceB serviceB, ServiceC serviceC, Executor asyncExecutor) {
        this.serviceB = serviceB;
        this.serviceC = serviceC;
        this.asyncExecutor = asyncExecutor;
    }

    private void asyncSaveCreationError(Exception e) {
        asyncExecutor.execute(() -> saveCreationError(e));
    }
    // 其余代码保持不变
}

第二步:测试用同步执行器构造实例

def "createAccount - should throw Exception and save error"() {
    given:
    // 同步执行器,提交的任务直接在当前线程执行,无异步时序问题
    Executor syncExecutor = Runnable::run
    @Subject
    def subject = new ServiceAImpl(serviceB, serviceC, syncExecutor)

    when:
    subject.createAccount("userId")

    then:
    1 * serviceB.createUserAccount(_) >> { throw new Exception() }
    thrown(Exception)
    1 * serviceC.save(_)
    0 * _
}

该方案不需要BlockingVariable,测试逻辑更简洁,运行稳定性更高。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:15:06