[英]Unit Testing show action of a controller with findwhere in grails
[英]Grails unit testing: error while redirecting to an action of another 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
//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”(重定向中的书,电影和TVShow控制器看起来为null,我不知道如何注入它们,因为它们不是控制器类中的字段)。
java.lang.NullPointerException
at ivvq.ItemUserController.$tt__commentItem(ItemUserController.groovy:138)
这是我在测试类中的代码部分:
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 != ""
很快,我打算做的是让用户对项目进行评论,并在提交评论后对同一项目进行评论。
注意:我正在使用Grails 2.3.11
我遇到了类似的情况,最终改变了我的重定向样式。 现在我使用这样的东西:
redirect(uri: "/controller/action", params: redirectParams)
对于您的情况,重定向如下所示:
redirect(uri: "/book/show", params: [id: book.id])
注意:我没有对此进行测试,但是应该非常接近。 params
只是要发送给下一个方法的参数映射。 那时,这对我的所有单元测试都有效。
对重定向风格的文档是在这里 ,如果是有帮助的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.