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

如何用StepVerifier测试方法抛出异常?空列表测试遇NPE问题

问题原因排查
  1. 方法名拼写错误:测试代码中调用的是productService.saveAlll(products),多了一个字母l,实际服务中的方法是saveAll。Groovy中调用不存在的方法会返回null,传入StepVerifier.create(null)就会触发NullPointerException。
  2. 异常处理方式不匹配:服务中传入空列表时是同步抛出异常(方法执行时直接throw,未进入Reactive流),而StepVerifier是用来验证Reactive流(Flux/Mono)中的异步异常,无法捕获这种同步抛出的异常。
解决办法

方案一:修正测试代码适配同步异常

直接使用Spock的原生异常断言来验证同步抛出的异常,同时修正方法名拼写:

def "Empty product list should throw an exception when saving products"() {
    given:
    def products = []

    when:
    productService.saveAll(products)

    then:
    def exception = thrown(IllegalArgumentException)
    exception.message == "Cannot save null or empty list of products!"
}

方案二:修改服务代码让异常进入Reactive流(可选)

如果希望异常在Reactive流中抛出,调整服务代码返回Flux.error()而非直接同步抛异常,此时可以用StepVerifier验证:

修改后的服务代码

public class ProductService {
                          
    private final ProductRepository productRepository;

    public Flux<Product> saveAll(List<Product> products) {
        if(ObjectUtils.isEmpty(products)){
            return Flux.error(new IllegalArgumentException("Cannot save null or empty list of products!"));
        }
        return productRepository.saveAll(products);
    }
}

对应的测试代码

def "Empty product list should throw an exception when saving products"() {
    given:
    def products = []

    when:
    def result = productService.saveAll(products)

    then:
    StepVerifier.create(result)
        .expectError(IllegalArgumentException)
        .verify()
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:47:27