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?
In Spock we can use the thrown() method to check for exceptions. We can use it in a then: block of our test.
The JUnit TestRunners will catch the thrown Exception regardless so you don't have to worry about your entire test suite bailing out if an Exception is thrown. This is the best answer.
Stubs are fake classes that come with preprogrammed return values. Mocks are fake classes that we can examine after a test has finished and see which methods were run or not. Spock makes a clear distinction between the two as mocks and stubs , as we will see in the sections to follow.
I believe your then
block needs to be fixed. Try the following syntax:
then: thrown CustomException
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With