繁体   English   中英

在使用render进行控制器方法的单元测试期间,Grails无法在null对象上调用getTimeZone()

[英]Grails cannot invoke getTimeZone() on null object during unit testing of method of controller with render

我有一个问题单元测试我的控制器方法。

@Transactional
def saveComment(){
    BlogPost post = BlogPost.findById(params.id)
    Comment comment = new Comment(author:params.author,comment:params.comment)
    comment.save(flush:true)
    post.addToComments(comment)
    post.save(flush:true)
    post.refresh()
    render(template:'commentsTemplate', collection:post.comments.reverse())
}

当它尝试渲染模板时出现问题。

<div class="row">
    <span>
        <font color="red"><b><span class="comment-author">${it.author}</span></b> <span class="comment-date-created" title="${it.dateCreated}"><g:formatDate format="MMM dd, yyyy" date="${it.dateCreated}"/> at <g:formatDate format="hh:mm aaa" date="${it.dateCreated}"/></span></font>
    </span>
</div>
<div class="comment-text row">${it.comment}</div>
<hr>
<br>

它会引发以下错误:

org.grails.web.servlet.mvc.exceptions.ControllerExecutionException: Error processing GroovyPageView: [views/blogPost/_commentsTemplate.gsp:3] Error executing tag <g:formatDate>: Cannot invoke method getTimeZone() on null object

当我在调试器模式中单步执行代码时,日期肯定是填充的,我的实际应用程序工作得很好。 只是这个单元测试失败了。

void "Test that the saveComment action adds a comment to the blog post"(){
        when:
            populateValidParams(params)
            BlogPost post = new BlogPost(params)
            post.save(flush: true, validate: false)
            params.author = 'Author'
            params.comment = 'This is a comment'
            params.id = 1
            params.dateCreated = new Date()
            params.post = post
            controller.saveComment()
            Comment comment = post.comments[0]

        then:
            post.comments.size() == 1
            comment.author == 'Author'
            comment.comment == 'This is a comment'
    }

我只是在试图解决问题所在的问题时遇到了麻烦。 特别是我知道评论的日期对象肯定在那里并且有时区。

要解决此问题,请在groovy文件的静态块中使用以下代码:

static doWithSpring = {grailsTagDateHelper(DefaultGrailsTagDateHelper)}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM