Grails Unit testing a function with session object
- by Suganthan
I having a Controller like
def testFunction(testCommand cmdObj) {
if (cmdObj.hasErrors()) {
render(view: "testView", model: [cmdObj:cmdObj])
return
} else {
try {
testService.testFunction(cmdObj.var1, cmdObj.var2, session.user.username as String)
flash.message = message(code: 'message')
redirect url: createLink(mapping: 'namedUrl')
} catch (GeneralException error) {
render(view: "testView", model: [cmdObj:cmdObj])
return
}
}
}
For the above controller function I having a Unit test function like:
def "test function" () {
controller.session.user.username = "testUser"
def testCommandOj = new testCommand(
var1:var1,
var2:var2,
var3:var3,
var4:var4
)
testService service = Mock(testService)
controller.testService = service
service.testFunction(var2,var3,var4)
when:
controller.testFunction(testCommandOj)
then:
view == "testView"
assertTrue model.cmdObj.hasErrors()
where:
var1 | var2 | var3 | var4
"testuser" | "word@3" | "word@4" | "word@4"
}
When running this test function I getting the error like Cannot set property 'username' on null object, means I couldn't able to set up the session object. Can someone help to fix this. Thanks in advance