Dave
Dave

Reputation: 8897

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)

Upvotes: 4

Views: 4974

Answers (4)

prayagupadhyay
prayagupadhyay

Reputation: 31222

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

Upvotes: 1

JustmeVSI
JustmeVSI

Reputation: 183

You need to be running the integration tests as grails tests not jUnit.

Upvotes: 1

Humberto
Humberto

Reputation: 11

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

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

Upvotes: 1

Gregg
Gregg

Reputation: 35864

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

Upvotes: 2

Related Questions