Spock throw exception test

60,223

Solution 1

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

then:
thrown CustomException

Solution 2

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"

Solution 3

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()
Share:
60,223
Piotr Sobolewski
Author by

Piotr Sobolewski

I love java world

Updated on March 11, 2021

Comments

  • Piotr Sobolewski
    Piotr Sobolewski about 3 years

    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?

  • Steve Gelman
    Steve Gelman over 4 years
    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?