如何使用Hamcrest来测试异常? [英] How to use Hamcrest to test for exception?

查看:228
本文介绍了如何使用Hamcrest来测试异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  def f(String s){
assert!s?.contains ('。')
}

可以使用什么Hamcrest匹配来测试断言?我知道我可以使用 try / catch 块,但我更喜欢将测试的圈复杂性保持为1。 p>

解决方案

编辑

使用Hamcrest,你可以这样写:

  assertThat({f('hi.ho')},thrown(MyException) )

您将需要 ThrownMatcher.thrown(..) matcher,我写的只是为了好玩。



请参阅
$ b



$ b

例如,您可以使用 GroovyTestCase 执行这:

  shouldFail(MyException,{/ *代码应该抛出MyException * /})

最后,如果您认真对待使用Spock进行测试:

http://code.google.com/p/spock/wiki/SpockBasics



示例

  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来测试异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆