Spock抛出异常测试

Pio*_*ski 16 java groovy unit-testing 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());
}
Run Code Online (Sandbox Code Playgroud)

我写了测试:

def "some test"() {
    given:
    bean.methodName(_) >> {throw new AnotherCustomExceptio ("Sth wrong")}
    def order = new Order();
    when:
    validator.validate(order )
    then:
    final CustomException exception = thrown()
}
Run Code Online (Sandbox Code Playgroud)

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

小智 18

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

then:
thrown CustomException
Run Code Online (Sandbox Code Playgroud)


Dav*_*ave 16

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

then:
def e = thrown(CustomException)
e.message == "Some Message"
Run Code Online (Sandbox Code Playgroud)


Aja*_*mar 12

then 可能有多种方法来处理异常:

thrown(CustomException)
Run Code Online (Sandbox Code Playgroud)

或者

thrown CustomException
Run Code Online (Sandbox Code Playgroud)

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

then:

noExceptionThrown()
Run Code Online (Sandbox Code Playgroud)

  • “doThrow”和“when”语句似乎都来自 Mockito。Mockito 语句是否可以与 Spock 模拟一起使用,或者模拟对象是否必须通过 Mockito 创建? (3认同)