Unit testing Grails单元测试:重定向到另一个控制器的操作时出错
我有一个控制器动作,看起来像这样Unit testing Grails单元测试:重定向到另一个控制器的操作时出错,unit-testing,grails,grails-controller,Unit Testing,Grails,Grails Controller,我有一个控制器动作,看起来像这样 //An action inside itemUserController def commentItem() { String comment = params['itemComment'] User user = session['currentUser'] String title = params['title'] def isBook = false, isTVShow = false, isMovie = false
//An action inside itemUserController
def commentItem() {
String comment = params['itemComment']
User user = session['currentUser']
String title = params['title']
def isBook = false, isTVShow = false, isMovie = false
//I do some manips here......
//and finally...
if(isBook)
redirect(controller: "book", action: "show", id: book.id)
if(isMovie)
redirect(controller: "movie", action: "show", id: movie.id)
if(isTVShow)
redirect(controller: "TVShow", action: "show", id: tvShow.id)
}
我的问题是测试这个,在单元测试和集成中进行了尝试,但在包含重定向的行中出现了相同的错误“NullPointerException”(看起来重定向中的book、movie和TVShow控制器为null,我不知道如何注入它们,因为它们不是控制器类中的字段)
下面是我在测试类中的代码部分:
when: "User tries to comment an item with an empty comment title and an empty comment text"
itemUserController.session['currentUser'] = user;
itemUserController.params['itemComment'] = ""
itemUserController.params['title'] = ""
itemUserController.params['itemBookId'] = book.id
itemUserController.commentItem()
then: "The user has an error message and the comment isnt posted"
itemUserController.flash.error != ""
很快,我打算做的是让用户对一个项目发表评论,并在提交评论后呈现相同的项目
注意:我使用的是Grails2.3.11我遇到过类似的情况,最终改变了重定向的风格。现在我使用这样的方法:
redirect(uri:“/controller/action”,参数:redirectParams)
对于您的情况,重定向如下所示:
重定向(uri:“/book/show”,参数:[id:book.id])
注意:我没有测试这个,但是应该非常接近。params
只是要发送到下一个方法的参数映射。这在我所有的单元测试中都起到了作用
重定向样式的文档是,如果有帮助的话
when: "User tries to comment an item with an empty comment title and an empty comment text"
itemUserController.session['currentUser'] = user;
itemUserController.params['itemComment'] = ""
itemUserController.params['title'] = ""
itemUserController.params['itemBookId'] = book.id
itemUserController.commentItem()
then: "The user has an error message and the comment isnt posted"
itemUserController.flash.error != ""