Spock throw exception test
Asked Answered
N

3

58

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?

Nenitanenney answered 31/3, 2014 at 8:36 Comment(4)
Can you expand the context of the Java Code, showing bean and validator, Order?Keep
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.Cartouche
Have you resolved this?Obduce
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?Nenitanenney
L
73

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

then:
thrown CustomException
Linskey answered 4/3, 2015 at 20:7 Comment(0)
Q
66

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"
Quicklime answered 23/8, 2019 at 7:18 Comment(0)
A
12

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()
Appetence answered 16/5, 2017 at 5:0 Comment(2)
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?Nightclub
@SteveGelman by "when", are you referring to the Spock when: block label?Zacynthus

© 2022 - 2024 — McMap. All rights reserved.