spock测试框架对异常的测试使用throw和notThrown方法,有如下的方式:
1 thrown()方法
如果我们知道某个被测试的方法会抛出异常,但这个已擦黑给你是我们所容忍的,这种情况需要怎么测试呢?有两种方法:
(1)try-catch 捕获,代码如下:
def "test exception with try-catch"() {
when:
int a = 1
int b = 0
int c = 2
Exception ex = null
try {
c = (a / b)
} catch(Exception e) {
ex = e
}
then:
ex instanceof ArithmeticException
}
这样测试代码的可读性差,而且也写起来麻烦,所以spock框架提供了thrown()方法。
(2)使用thrown()方法
/**
* 测试一个方法抛出异常,可以使用try-catch在when语句块中捕获验证,但是写起来比较繁琐
* 所以,Spock测试框架中可以使用thrown()来表示这种现象,并且可以返回异常的实例
*/
def "test Thrown"() {
when:
int a = 1
int b = 0
int c = 2
c = (a / b)
then:
def ex = thrown(Exception)
ex instanceof ArithmeticException
// ArithmeticException 异常时我们预料之中的
}
这样就使得代码更加优雅有条理。
2 notThrown()方法
如果我们明确知道某个方法不应该抛出某种异常,需要怎样在spock测试时表示呢?这是就使用notThrown()方法,如下:
/**
* notThrown() 表示被测试的方法不会抛出某种异常
*/
def "HashMap accepts null key"() {
given:
def map = new HashMap()
when:
map.put(null, "elem")
then:
notThrown(NullPointerException)
}
我们知道hashMap允许null作为key,所以我们就可以断言,put(null,v)方法不会抛出异常,也就是notThrown()的语义。这种情景也可以根据实际情况应用在我们自己的业务测试中。