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()
Comments
-
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 thetry{}catch
block I catch this exception and throw aCustomException
so I expected that my method will throwCustomException
and notAnotherCustomExceptio
. How do I test it? -
Steve Gelman over 4 yearsBoth 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?