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
.我该如何测试?
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)