0

I need something like:

assertThat({throw new Exception("hey!")}).throws(Exception).hasMessage("hey!");

In Java I used a standard approach, but it's too much for a language with closures:

try{
    throw new Exception("hey!");
    fail("not thrown");
}catch (Exception e){
    assertThat(e).hasMessage("hey!");
}

Using frameworks like JUnit, Hamcrest, Fest or Mockito is very welcome.

Andrey Chaschev
  • 16,160
  • 5
  • 51
  • 68
  • possible duplicate of [How to use Hamcrest to test for exception?](http://stackoverflow.com/questions/19256175/how-to-use-hamcrest-to-test-for-exception) (not sure if this completely covers your use-case) – Oliver Charlesworth Dec 19 '13 at 14:31
  • Thank you for a quick reply. I have found a close alternative with `GroovyAssert.shouldFail`, but can't check a message returned. – Andrey Chaschev Dec 19 '13 at 14:43
  • It appears that the return value of `shouldFail` is the message, which allows you to assert on it: http://mrhaki.blogspot.co.uk/2009/11/groovy-goodness-testing-for-expected.html (I haven't tried this, no idea if it actually works ;)) – Oliver Charlesworth Dec 19 '13 at 14:45
  • Thank you, it actually does, I've put an example below on what I have found. – Andrey Chaschev Dec 19 '13 at 14:54

1 Answers1

2

The closest match I have found with a help of @OliCharlesworth is assertThat from the FestAssert library and shouldFail from GroovyAssert:

assertThat(shouldFail(Exception, {throw new Exception("hey")})).hasMessage("hey")
Andrey Chaschev
  • 16,160
  • 5
  • 51
  • 68