斯波克抛出异常测试

54

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


你能扩展Java代码的上下文,展示“bean”、“validator”、“Order”吗? - dmahapatro
以上展示的生产代码和测试代码如何结合在一起并不清楚。(例如,在生产代码中没有对 bean#methodName 的调用)。很可能,异常并未从上面显示的 try 块中抛出。您应该能够在调试器中验证这一点。 - Peter Niederwieser
你解决了吗? - Jared Burrows
我不知道 :) 我在一年前写下了这个问题 :) 但是,将“bean.methodName(_) >> {throw new AnotherCustomExceptio ("Sth wrong")}”移动到“when”部分怎么样?你能尝试一下吗? - Piotr Sobolewski
3个回答

69

我认为你的then块需要修复。尝试以下语法:

then:
thrown CustomException

59

如果您想评估抛出的异常消息,您可以像这样做:

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

11

处理 then 中的异常有多种方法:

thrown(CustomException)

或者

thrown CustomException

我们可以检查测试用例中是否没有抛出任何异常 -

then:

noExceptionThrown()

3
“doThrow”和“when”语句似乎都来自于Mockito。Mockito的语句能否与Spock Mock一起使用,或者必须通过Mockito创建Mock对象? - Steve Gelman
@SteveGelman,您所说的“when”是指Spock when:块标签吗? - cellepo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接