4

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.

Noel Yap
  • 18,822
  • 21
  • 92
  • 144

1 Answers1

5

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 )
Renato
  • 12,940
  • 3
  • 54
  • 85
  • I know about Spock but due to constraints cannot use it for testing. – Noel Yap Oct 08 '13 at 21:44
  • I like the Hamcrest answer, but would feel better up-voting it and checking it if it were a separate answer. – Noel Yap Oct 09 '13 at 20:10
  • 1
    I agree, but I don't think it's ok to remove an answer or answer twice... so I just edited to have the ACTUAL answer first, and my suggestion about Spock last so the answer contents is still the same. – Renato Oct 09 '13 at 20:30
  • 1
    I think it's perfectly fine to answer twice. Did you try? – Noel Yap Oct 09 '13 at 22:16