Spock抛出异常测试

时间:2014-03-31 08:36:42

标签: java unit-testing groovy spock

我用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。我该如何测试?

3 个答案:

答案 0 :(得分:13)

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

then:
thrown CustomException

答案 1 :(得分:2)

例如,如果您要评估引发的Exception消息,则可以执行以下操作:

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

答案 2 :(得分:0)

while (not Q[ClientIdx].Empty) and (Today - Q[ClientIdx].Peek > 90) 
    Q[ClientIdx].Remove  //dequeue too old records
VisitCount = Q.Count