我用Spock测试Java代码。我测试以下代码:

 try {
    Set<String> availableActions = getSthAction()
    List<String> goodActions = getGoodAction()
    if (!CollectionUtils.containsAny(availableActions ,goodActions )){
       throw new CustomException();
    }
} catch (AnotherCustomExceptio e) {
     throw new CustomException(e.getMessage());
}

我写了测试:
def "some test"() {
    given:
    bean.methodName(_) >> {throw new AnotherCustomExceptio ("Sth wrong")}
    def order = new Order();
    when:
    validator.validate(order )
    then:
    final CustomException exception = thrown()
}

它失败,因为抛出了AnotherCustomExceptio。但是在try{}catch块中,我捕获了此异常并抛出了CustomException,因此我希望我的方法将抛出CustomException而不是AnotherCustomExceptio。我该如何测试?

最佳答案

我相信您的then块需要修复。尝试以下语法:

then:
thrown CustomException

10-06 12:54