Java Programming Tutorials

Java programming tutorials with many code examples!

Spock Framework Mock throw exception


Spock Framework Mocks allow to easily test handling of unexpected behaviors and inspect thrown exceptions. See how to throw and handle expected exceptions in unit tests!


As base classes lets use UserController and UserService defined in tutorial on Spock Framework Mock.

Sometimes there’s a need to test handling of exceptions in code and we would like to throw them from Mock. This example shows how to do that:

package com.farenda.solved

import spock.lang.Specification

class MockThrowExceptionTest extends Specification {

    // an interface with two methods: exists(user), add(user)
    def userService = Mock(UserService)

    // a controller to test, that will use mock of the service:
    def controller = new UserController(userService: userService)

    def 'should throw exception for invalid username'() {
        def username = 'Joffrey Baratheon'
        userService.exists(_ as User) >> false
        userService.add(_ as User) >> { User user ->
            throw new IllegalArgumentException(


        def e = thrown(IllegalArgumentException)
        e.message == username

It the example Mock for exists() method could have been omitted, because default value is false anyway.

The important point here is that we throw an exception from Groovy closure and expect it using Spock’s thrown(Type) method. Nice thing is that we can assign the exception to a variable and assert its data.

When the exception would not be thrown, then Spock Framework prints the following error:

Expected exception of type 'java.lang.IllegalArgumentException', but no exception was thrown
      at org.spockframework.lang.SpecInternals.checkExceptionThrown(
      at org.spockframework.lang.SpecInternals.thrownImpl(
      at com.farenda.solved.MockThrowExceptionTest.should throw exception for invalid username(MockThrowExceptionTest.groovy:26)

Of course there is also complementary method that allows to assert that an exception has not been thrown:

def 'should not throw'() {

  // other assertions

Now, you’ve got another tool in your Spock testing toolbox! :-)

Share with the World!
  • UATP

    Is it possible for you to add the print out of the error mentioned in the line…
    “When the exception would not be thrown, then Spock Framework prints the following error:”

    • farenda

      Fixed. Thank you for feedback! :-)

    • Fixed! Thank you for feedback! :-)