Continuing with the series of posts on Spock framework for Groovy, let’s discuss testing the exceptions for the Calculator class. The Calculator class with two methods add and divide are given below.
//Calculator.groovy class Calculator { def add(num1,num2){ num1 + num2 } def divide(num1,num2){ if(num2 == 0) throw new Exception("Invalid argument. Cannot be zero") num1/num2 } }
Say you want to test the divide function in the CalculatorSpec.groovy. Spock provides two functions that thrown and notThrown that can be used to test the exception rules. Let’s write a feature to check if the exception is thrown and another feature to check if the exception is not thrown. The code is given below.
class CalculatorSpec extends Specification{ Calculator calc def setup(){ calc = new Calculator() } def cleanup(){ calc = null; } def "divide by zero"(){ when: calc.divide(12, 0) then: Exception e = thrown(Exception) e.message == "Invalid argument. Cannot be zero" } def "divide"(){ when: calc.divide(12, 10) then: notThrown(Exception) } }
In the code above we have two feature methods “divide by zero” that tests if the exception is thrown and also the error message, “divide” that can be used to test if the exception is not thrown in case of valid arguments.
In the last three posts we’ve discussed using various features of Spock framework. In the next post we’ll discuss mocking behavior with Spock.