Exception Testing using Spock in grails

04 / May / 2011 by Uday Pratap Singh 0 comments

Testing was never so easy and intuitive before the use of Spock. Earlier when I was using grails unit testing, it never attracted me to write more and more test cases but with Spock you always keen to test each and every line of your code, testing the exceptions is one of them.

You can always test the exceptions in grails unit test as well but with Spock it looks more clean and more readable. For example you have a method which throws exception like

String getUserType(int age){
    if(age<=0){
        throw new MyException("Invalid age")
    }else if( age>0 && age<50){
        return "Young"
    }else{
        return "Old"
    }
}

Now we will write the test case of this method for checking whether exception is thrown for invalid inputs or not.

def "exception should be thrown only for age less than or equal to 0"{
    given:
        String type = getUserType(34)
    expect:
        type == "Young"
        notThrown(MyException)
    when:
        type = getUserType(0)
    then:
        MyException me = thrown()
        me.message == "Invalid age"
}

This is how we have tested whether exception is thrown for invalid input or not.

Hope it helps
Uday Pratap Singh
uday@intelligrape.com

FOUND THIS USEFUL? SHARE IT

Leave a comment -