简体   繁体   中英

Trouble getting grailsApplication reference from integration test

I'm using Grails 1.2.1 and trying to write an integration test for one of my service classes. The service method i want to test is ...

class UtilityService {

boolean transactional = false

def grailsApplication

def isAuthorizedHost(String hostIpAddr) {
    // Simple validation
    if (hostIpAddr == null || hostIpAddr.length() == 0)
        return false;
    //
    def allowedDomains = grailsApplication.config.proxy.allowedDomains
...

but when writing my integration test, I'm unable to get a non-null reference to the grailsApplication object ...

class UtilityServiceTests extends GrailsUnitTestCase {

def grailsApplication


void testIsAuthorizedHost() {
    def utilityService = new UtilityService()
    utilityService.grailsApplication = grailsApplication
    def ret = utilityService.isAuthorizedHost("127.0.0.1")
    assertTrue( ret )
}

Here is the error. How do I get the reference? - Dave

Cannot get property 'config' on null object

java.lang.NullPointerException: Cannot get property 'config' on null object at com.nna.tool.proxy.Utility.UtilityService.isAuthorizedHost(UtilityService.groovy:26) at com.nna.tool.proxy.Utility.UtilityService$isAuthorizedHost.call(Unknown Source) at com.nna.tool.proxy.Utility.UtilityServiceTests.testIsAuthorizedHost(UtilityServiceTests.groovy:20)

See the answer here. It might also work in your situation. You can just put that code in the tests setup() method...

Grails Functional Testing - grailsApplication.config is null within controllers and services

您需要运行集成测试,因为grails测试不是jUnit。

Constructing grailsApp using DefaultGrailsApplication would work.

import org.codehaus.groovy.grails.commons.DefaultGrailsApplication

class UtilityServiceTests extends GrailsUnitTestCase {
    def grailsApplication = new DefaultGrailsApplication()

    void testIsAuthorizedHost() {
        def utilityService = new UtilityService()
        utilityService.grailsApplication = grailsApplication
        def ret = utilityService.isAuthorizedHost("127.0.0.1")
        assertTrue( ret )
     }
}

References

grails-core / grails-core / src / main / groovy / org / codehaus / groovy / grails / commons / DefaultGrailsApplication.java

I think the grailsApplication property is only available in the controller and views, for a service

Try ApplicationHolder.application.config.proxy.allowedDomains instead.

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