September 30, 2016

Spocklight: Check No Exceptions Are Thrown At All

In a previous post we learned that we can check a specific exception is not thrown in our specification with the notThrown method. If we are not interested in a specific exception, but just want to check no exception at all is thrown, we must use the noExceptionThrown method. This method return true if the called code doesn't throw an exception.

In the following example we invoke a method (cook) that can throw an exception. We want to test the case when no exception is thrown:


import spock.lang.Specification

class RecipeServiceSpec extends Specification {
    def """If the recipe is cooked on the right device and
           for the correct amount of minutes,
           then no exception is thrown"""() {
        def recipeService = new RecipeService()
        def recipe = new Recipe(device: 'oven', time: 30)

        recipeService.cook(recipe, 30, 'oven')

        then: 'no exceptions must be thrown'

class RecipeService {
    def cook(Recipe recipe, int minutes, String device) {
        if (minutes > recipe.time) {
            throw new BurnedException()
        if (device != recipe.device) {
            throw new InvalidDeviceException("Please use $recipe.device for this recipe.")

class Recipe {
    int time
    String device

import groovy.transform.InheritConstructors

class BurnedException extends RuntimeException {

class InvalidDeviceException extends RuntimeException {

Written with Spock 1.0-groovy-2.4.