Initializations in Grails Unit Test Cases
Most of us have experienced how important the Unit test cases are for our code base. I feel the other thing that is equally important, is the speed at which we can write the unit test cases. In Unit Testing, initializing different objects in setup of the test case (e.g., while testing a method which queries the database) can become a pain, especially when the objects to be initialized have many attributes and relationships. Grails/Spock have simplified initialization process for us. All we need to is to initialize just the required attributes of the objects, along with the id field,e.g., while testing a method of a class Student :
[java]
class Student {
String name
String fathersName
String address
static belongsTo = [school: School]
static constraints = {
name(nullable: false)
fathersName(nullable: false)
address(nullable: false)
}
// METHOD TO BE TESTED
List<Student> findMySchoolsStudentsWithNamesLike(String nameLike) {
List<Student> students = Student.findAllBySchoolAndNameLike(this.school, ‘%’ + nameLike + ‘%’)
return students
}
}
[/java]
To test the method, a Spock test case with the simplified initializations will be like:
[java]
def "My School students are retrieved correctly"() {
setup:
School school = new School(id: 1)
List<Student> students = (1..10).collect {new Student(id: it, name: "name${it}", school: school)}
mockDomain(Student, students)
expect:
students[0].findMySchoolsStudentsWithNamesLike(‘1’).size() == 2
}
[/java]
Similar setup can work in Grail Unit test case.
Simplification of the initialization process has made Unit testing simpler and faster, thus allowing us to write more Unit test cases.
Cheers,
Imran Mir
imran@intelligrape.com
Great beat ! massage would like to apprentice at the same time as you amend your website, how could massage subscribe for a weblog website? The account aided me a acceptable deal. massage have been tiny bit acquainted of this your broadcast provided shiny transparent idea
It is the ideal facts on this topic I’ve viewed all week. Keep it up!
Pikalaina 50 – 1000€ hae lainaa – Euroloan- VälimuistissaPikalainan tarpeeseen euroloan.fi –palvelu tarjoaa täsmälainan, jossa voit itse määrittää laina-ajan ja … Pikalainan hakeminen on tehty helpoksi ja turvalliseksi.