Spock throw exception test

Piotr Sobolewski picture Piotr Sobolewski · Mar 31, 2014 · Viewed 37.7k times · Source

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?

Answer

Marcos Carceles picture Marcos Carceles · Mar 4, 2015

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

then:
thrown CustomException