How to use Hamcrest to test for exception?

后端 未结 1 810
天涯浪人
天涯浪人 2021-01-14 02:21

I have the following code:

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

What Hamcrest matcher can be used to test the assertion? I know

相关标签:
1条回答
  • 2021-01-14 02:59

    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 )
    
    0 讨论(0)
提交回复
热议问题