Reputation: 8897
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
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 )
}
}
Upvotes: 1
Reputation: 183
You need to be running the integration tests as grails tests not jUnit.
Upvotes: 1
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
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