Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grails spock testing failing with 'java.lang.IllegalArgumentException: ServletContext must not be null'

Tags:

java

grails

spock

I having a method in command class, which use messageSource.getMessage(...), as messageSource won't get injected into the commandClass. I use

def messageSource = Holders.applicationContext.getBean("messageSource") inside the commandClass.

My problem is when trying to write unit test this method,

@Before
void setup() {
    Holders.applicationContext.getBean("messageSource")
}

void "testFunction"() {
    //inside testFunction I am using messageSource
    given:
        //required things
    when:
        //call the function
    then:
        //assert
}

after testing this function, I getting the error

java.lang.IllegalArgumentException: ServletContext must not be null at grails.util.Holders.getApplicationContext(Holders.java:80)

Can someone suggest on how to resolve this one.

Update

@Validateable
class commandClass {
    //required fields and constraints
    def formatData(List<commandClass> commandObjs) {
        StringBuilder validationErrors
        commandObjs.each {commandObj->
            validationErrors = new StringBuilder()
            if(commandObj.hasErrors()) {
                commandObj.errors.allErrors.each {it ->
                    validationErrors.append(messageSource.getMessage(it, null)).append('\n')
                }
            }
            commandObj.metaClass.validationErrors = validationErrors
        }

    }
} 

Thanks in Advance

like image 227
Suganthan Madhavan Pillai Avatar asked Oct 23 '14 09:10

Suganthan Madhavan Pillai


1 Answers

I found the answer

void setup() {
    mockApplicationContext()
}

def static mockApplicationContext() {
    GrailsUnitTestMixin.initGrailsApplication()
    Holders.grailsApplication = GrailsUnitTestMixin.grailsApplication
    Holders.metaClass.'static'.getApplicationContext = { ->
        return GrailsUnitTestMixin.applicationContext
    }
    Holders.metaClass.applicationContext.getBean = { bean ->
        return GrailsUnitTestMixin.messageSource
    }
}

I 'll update more about the answer later

like image 140
Suganthan Madhavan Pillai Avatar answered Sep 23 '22 09:09

Suganthan Madhavan Pillai