简体   繁体   中英

grailsApplication not available in Domain class when running all Integration tests

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.

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'
    }

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.

我遇到了同样的问题,发现我的集成测试实现了导致问题的 ServiceUnitTest<>。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM