Ivan Longin
Ivan Longin

Reputation: 3353

Do GORM hook methods work in Grails integration test

I have simple question

Do GORM hooks method (beforeUpdate, afterLoad etc) work during integration tests? Are they evaluated?

I have integration test (my test class extends GroovyTestCase) and as I can see changes that I make in afterLoad method on my domain object doesn't seem to work (domain object stays the same after loading) and when I test it manually (run my app) it works (domain object is changed successfully). Also I cannot see any logs or prints to console from hook methods during integration tests.

Is this expected behavior or I am missing something?

Here is some code: I have PackageState domain object which has field accountID (Integer). In PackageState I have afterLoad hook:

def afterLoad() {
        this.accountID = 33333
    }

My test suite looks something like this :

void "test3"() {
        PackageState packageState1 = PackageState.findByAccountID(11111)
        assertEquals(33333, packageState1.accountID)
    }

Message is : junit.framework.AssertionFailedError: expected:<33333> but was:<11111>

So seems to me that hook is not called :/ ...

Thanks, Ivan

Upvotes: 3

Views: 562

Answers (1)

dmahapatro
dmahapatro

Reputation: 50245

You can integration test those event hooks by surrounding the dynamic method (or any other GORM method) by withNewSession as:

class PackageStateSpec extends IntegrationSpec {
    PackageState packageState1

    void "test something"() {
        given:
            PackageState.withNewSession{
                packageState1 = PackageState.findByAccountID(11111)
            }

        expect:
            packageState1.accountID == 33333
    }
}

Events will be registered with a new session every time when tested from integration tests.

Upvotes: 3

Related Questions