我有像
这样的控制器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
}
}
}
对于上述控制器功能,我有一个单元测试功能,如:
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"
}
运行此测试功能时,我收到Cannot set property 'username' on null object
这样的错误,意味着我无法设置会话对象。有人可以帮助解决这个问题。提前致谢
答案 0 :(得分:2)
由于您正在进行Grails控制器的单元测试,因此您可以直接将变量分配到会话对象中,就像在setup:block中这样使用params一样。我建议你先在会话中分配User对象然后就可以了:我稍微修改了你的代码:
def "test function" () {
setup:
User user = new User(username:'requiredUserName').save(flush:true,failOnError:true)
session.user = user
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"
}
这应该可以正常工作。唯一的问题是你没有在会话中分配User对象。