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
Spock throw exception test
提问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 AnotherCustomExceptio
is thrown. But in the try{}catch
block I catch this exception and throw a CustomException
so I expected that my method will throw CustomException
and not AnotherCustomExceptio
. How do I test it?
它失败,因为AnotherCustomExceptio
被抛出。但是在try{}catch
块中我捕获了这个异常并抛出了一个CustomException
所以我预计我的方法会抛出CustomException
而不是AnotherCustomExceptio
。我该如何测试?
采纳答案by Marcos Carceles
I believe your then
block 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"