How to use Hamcrest to test for exception?

北城余情 提交于 2019-12-19 09:20:42

问题


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.


回答1:


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 )


来源:https://stackoverflow.com/questions/19256175/how-to-use-hamcrest-to-test-for-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!