Question

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.

Was it helpful?

Solution

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 )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top