Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spock throw exception test

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?

like image 595
Piotr Sobolewski Avatar asked Mar 31 '14 08:03

Piotr Sobolewski


People also ask

How do you test exceptions in Spock?

In Spock we can use the thrown() method to check for exceptions. We can use it in a then: block of our test.

Should JUnit tests throw exceptions?

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.

What is mock in Spock?

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.


Video Answer


2 Answers

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

then: thrown CustomException 
like image 62
Marcos Carceles Avatar answered Sep 19 '22 20:09

Marcos Carceles


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" 
like image 32
Dave Avatar answered Sep 20 '22 20:09

Dave