Java Spock抛出异常测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22757014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:44:09  来源:igfitidea点击:

Spock throw exception test

javaunit-testinggroovyspock

提问by Piotr Sobolewski

I test Java code with Spock. I test this code:

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

I wrote test:

我写了测试:

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

And it fails because AnotherCustomExceptiois thrown. But in the try{}catchblock I catch this exception and throw a CustomExceptionso I expected that my method will throw CustomExceptionand not AnotherCustomExceptio. How do I test it?

它失败,因为AnotherCustomExceptio被抛出。但是在try{}catch块中我捕获了这个异常并抛出了一个CustomException所以我预计我的方法会抛出CustomException而不是AnotherCustomExceptio。我该如何测试?

采纳答案by Marcos Carceles

I believe your thenblock needs to be fixed. Try the following syntax:

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

then:
thrown CustomException

回答by Ajay Kumar

def "Exception Testing 1"(){
    given :
    def fooObject = mock(Foo);
    when:
    doThrow(RuntimeException).when(fooObject).foo()
    then:
    thrown RuntimeException
}

def "Exception Testing 2"(){
    given :
    def fooObject = Mock(Foo);
    when:
    when(fooObject.foo()).thenThrow(RuntimeException)
    then:
    thrown RuntimeException
}

回答by Dave

If you would like to evaluate for instance the message on the thrown Exception, you could do something like:

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

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