2
votes

Usually I was ending up writing test cases for a Domain by writing them for constraints and any custom methods(created by us in application) as we know we shouldn't test obvious.

But the time we started using coverage plugin, we found that our domains line of code is not fully covered which was due to gorm hooks(onInsert, beforeUpdate) that we never wrote test cases for.

Is there a way we can test these. One possible way that seems obvious but not suitable is to call another method(containing all code which was earlier in hooks) within these hooks and test that method only and be carefree for hooks.

Any solutions...

Edit

Sample code in domain that I want to unit-test:

class TestDomain{
   String activationDate
   def beforeInsert() {
      this.activationDate = (this.activationDate) ?: new Date()//first login date would come here though
      encodePassword()
   }
}

How can I unit-test beforeInsert or I would end up writing integration test case?

1
Perhaps you can post a code example and your respective unit test? - kazanaki
@kazanaki , please see my edit above. - Vinay Prajapati
Ok. But where is the unit test? What do you want to test? The beforeInsert method itself, or the fact that Grails calls it when you expect it to be called? - kazanaki
I think that Grails wil call these methods in both unit and integration tests. - kazanaki

1 Answers

3
votes

Perhaps a unit test like:

import grails.test.mixin.TestFor

@TestFor(TestDomain)
class TestDomainSpec extends Specification {
    def "test beforeSave"() {
        given:
            mockForConstraintsTests(TestDomain)
        when:
            def testDomain = new TestDomain().save(flush:true)
        then:
            testDomain.activationDate != null
    }
}