问题描述
我有以下代码:
def f(String s){
assert!s?.contains ('。')
}
可以使用什么Hamcrest匹配来测试断言?我知道我可以使用 try
/ catch
块,但我更喜欢将测试的圈复杂性保持为1。 p>
编辑
使用Hamcrest,你可以这样写: assertThat({f('hi.ho')},thrown(MyException) )
您将需要 ThrownMatcher.thrown(..)
matcher,我写的只是为了好玩。
请参阅执行这:
shouldFail(MyException,{/ *代码应该抛出MyException * /})
最后,如果您认真对待使用Spock进行测试:
示例
when:
f'something.something'
then:
thrown(TypeOfException)
I have the following code:
def f(String s) {
assert !s?.contains('.')
}
What Hamcrest matcher can be used to test the assertion? I know I can use a try
/catch
block but I prefer keeping the cyclomatic complexity of tests to one.
EDIT
If you REALLY must use Hamcrest, you could write something like:
assertThat( { f( 'hi.ho' ) }, thrown( MyException ) )
You will need the ThrownMatcher.thrown(..)
matcher which I wrote just for fun.
See Gist here.
But in Groovy, Hamcrest matchers can be easily replaced with more powerful constructs.
You could, for example, use GroovyTestCase to do this:
shouldFail( MyException, { /* code expected to throw MyException*/ } )
Finally, if you're serious about testing use Spock:
http://code.google.com/p/spock/wiki/SpockBasics
Example
when:
f 'something.something'
then:
thrown( TypeOfException )
这篇关于如何使用Hamcrest来测试异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!