斯波克抛出异常测试

2022-09-01 02:17:59

我用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()
}

它失败是因为被抛出。但是在块中,我捕获了这个异常并抛出了一个,所以我期望我的方法会抛出而不是。如何测试?AnotherCustomExceptiotry{}catchCustomExceptionCustomExceptionAnotherCustomExceptio


答案 1

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

then:
thrown CustomException

答案 2

例如,如果要评估抛出异常上的消息,可以执行如下操作:

then:
def e = thrown(CustomException)
e.message == "Some Message"

推荐