grailsApplication not available in Domain class wh

2019-08-10 04:57发布

I'm running into a problem when running integration tests in Grails. One of the domain classes in the project has a method that accesses the grailsApplication.config property. We have an integration test for one of our services that call this method in the domain class. When the test is run on its own using the command

grails test-app integration: com.project.MyTestSpec

The test runs fine and the domain class can access grailsApplication. However when the whole test suite is run using:

grails test-app integration

then the test fails with the error

java.lang.NullPointerException: Cannot get property 'config' on null object

When trying to access grailsApplication.config. It seems that when the tests are all run together grailsApplication is not being injected into the domain class. Has anyone come across this issue before?

From what I have read it seems to be a test pollution issue but as there is no setup happening in each integration test the problem is hard to track down.

2条回答
smile是对你的礼貌
2楼-- · 2019-08-10 05:08

I came across this issue with grails 3. If you are testing a Domain, you have to setup (testing with spock) at the begining of the test:

def setup() {
        Holders.grailsApplication = new DefaultGrailsApplication()
        Holders.grailsApplication.config.property.code = '1234'
    }
查看更多
该账号已被封号
3楼-- · 2019-08-10 05:28

I'm not sure what the issue is, but this must be a test pollution issue where yours any one of the test case is doing something with grailsApplication using meta class. Because this seems to work fine for me.

As a workaround you can avoid using injected grailsApplication and use the Holders class instead like the following:

package com

import grails.util.Holders

class User {

    // def grailsApplication

    String email
    String name

    String getTitle() {
        return Holders.getConfig()["app.title.prefix"] + name
        // Or
        //return Holders.grailsApplication.config["app.title.prefix"] + name       
    }
}

This way, you are not dependent upon the dependency injection.

查看更多
登录 后发表回答