Skip to content

Unit test: Domain classes

pschneider-manzell edited this page Dec 9, 2012 · 2 revisions

Unit tests for domain classes

Testing dynamic finders

e.g. test if you can find an author by it's firstname and lastname after creating a new instance

def "find author by firstname and lastname"() {
      setup:
      mockDomain(Author)

      when:
      new Author(firstname: firstname,lastname:lastname).save()

      then:
      Author.findByFirstnameAndLastname(firstname,lastname) != null

      where:
      firstname = "John"
      lastname = "Doe"
}

Find more examples here:

  • AuthorSpec
  • BookSpec

Testing constraints

e.g. test constraints (blank:false,maxSize:20) of attribute firstname

def "firstname constraints"() {
	setup:
	mockForConstraintsTests(Author)

	when:
	def author = new Author(firstname: firstname, lastname: "Doe")
	author.validate()

	then:
	author.hasErrors() == !valid

	where:

firstname | valid
"123456789012345678901" | false //Firstname must not have more than 20 characters 
"12345678901234567890" | true
"" | false //Firstname must not be blank

}

Find more examples here:

  • AuthorSpec
  • BookSpec

Clone this wiki locally