Writing test cases for Domain class Using Spock

16 / Jun / 2015 by Sanchit . 0 comments

The agenda of this blog is to demonstrate how to write basic validation test cases for domain class in grails application.

Create a domain class User with some basic constraints.

[java]
package com.ttn.testing

class User {
String emailId
String name

static constraints = {
emailId nullable: false, blank: false
name nullable: true, blank: false, minSize: 3, maxSize: 20
}
}
[/java]

Add dependencies for spock in BuildConfig.groovy
[java]
dependencies {
test "org.spockframework:spock-grails-support:0.7-groovy-2.0"
}

plugins {
test(":spock:0.7") {
exclude "spock-grails-support"
}
[/java]

documentation of spock plugin : https://grails.org/plugin/spock

1. Test case for required fields validation.

[java]
@Unroll("test for required field validation")
def "test for required field validation"() {

when: "Create user instance"
User user = new User(emailId: emailId)

then: "emailId should not be null"
user.validate() == expectedResult

where:
testDescription | emailId | expectedResult
"valid test" | ‘sanchit@sanchit.com’| true
"null test" | null | false
}
[/java]

2. Test case for min length validation

[java]
@Unroll("min length validation")
def "min length validation"() {

when: "Create user instance"
User user = new User(emailId: "sanchit@sanchit.com", name: name)

then: "name minimun of 3 char"
user.validate() == expectation

where:
testDescription | name | expectation
"valid test" | "sanchit" | true
"min length test" | "sa" | false
}
[/java]

Grails automatically create a UserSpec.groovy in test/unit folder for writing the test cases.

Command to run test cases : grails test-app unit: User

Above command execute the test case, generate the report and return the path of report file.
ex-
Tests PASSED – view reports in
/home/sanchit/work/workspace/projects/testingWithSpock/target/test-reports

Copy the path and open it in browser to see the test report.

In this way we can validate the domain class constraints using spock.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *