53

I test Java code with Spock. I test this code:

 try {
    Set<String> availableActions = getSthAction()
    List<String> goodActions = getGoodAction()
    if (!CollectionUtils.containsAny(availableActions ,goodActions )){
       throw new CustomException();
    }
} catch (AnotherCustomExceptio e) {
     throw new CustomException(e.getMessage());
}

I wrote test:

def "some test"() {
    given:
    bean.methodName(_) >> {throw new AnotherCustomExceptio ("Sth wrong")}
    def order = new Order();
    when:
    validator.validate(order )
    then:
    final CustomException exception = thrown()
}

And it fails because AnotherCustomExceptio is thrown. But in the try{}catch block I catch this exception and throw a CustomException so I expected that my method will throw CustomException and not AnotherCustomExceptio. How do I test it?

Dror Bereznitsky
  • 20,048
  • 3
  • 48
  • 57
Piotr Sobolewski
  • 2,024
  • 4
  • 28
  • 42
  • Can you expand the context of the Java Code, showing `bean` and `validator`, `Order`? – dmahapatro Mar 31 '14 at 14:29
  • It's not clear how the production code and test code shown above fit together. (E.g. there is no call to `bean#methodName` in the production code.) Most likely, the exception isn't thrown from the try-block shown above. You should be able to verify this in the debugger. – Peter Niederwieser Mar 31 '14 at 18:27
  • Have you resolved this? – Jared Burrows May 13 '15 at 07:03
  • I do not know :) I wrote this question year ago :) But, what about move " bean.methodName(_) >> {throw new AnotherCustomExceptio ("Sth wrong")}" to "when" section. Could you try? – Piotr Sobolewski May 13 '15 at 07:06

3 Answers3

68

I believe your then block needs to be fixed. Try the following syntax:

then:
thrown CustomException
aldrael
  • 547
  • 1
  • 5
  • 13
Marcos Carceles
  • 912
  • 1
  • 10
  • 11
54

If you would like to evaluate for instance the message on the thrown Exception, you could do something like:

then:
def e = thrown(CustomException)
e.message == "Some Message"
Dave
  • 1,417
  • 14
  • 23
10

There could be multiple ways to handle the exception in then:

thrown(CustomException)

or

thrown CustomException

As well we can check if no Exception is thrown in the Test case -

then:

noExceptionThrown()
Ajay Kumar
  • 4,864
  • 1
  • 41
  • 44
  • 3
    Both the "doThrow" and "when" statements seem to be from Mockito. Will Mockito statements work with a Spock mock, or does the mock object have to be created through Mockito? – Steve Gelman Aug 30 '19 at 13:55
  • @SteveGelman by "when", are you referring to the [Spock `when:` block label](https://spockframework.org/spock/docs/1.3/all_in_one.html#_when_and_then_blocks)? – cellepo May 17 '23 at 18:43