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

Unit testing Grails在使用render对控制器的方法进行单元测试期间,无法对null对象调用getTimeZone(),unit-testing,grails,gsp,Unit Testing,Grails,Gsp,我在单元测试控制器方法时遇到问题 @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.s

我在单元测试控制器方法时遇到问题

@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>

我只是不知道问题出在哪里。特别是我知道注释的date对象肯定在那里并且有时区。

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

静态定位销弹簧={ grailsTagDateHelper(默认grailsTagDateHelper)
}

嗯。。。在单元测试中,您只有控制器代码,周围没有grails应用程序。您必须提供上下文。“无法在空对象上调用getTimeZone”可能不是指您的日期。它可能试图查看grails应用程序主机(即服务器)而没有找到它吗?事实证明,null对象引用了的标记库的一部分,我假设它没有被实例化,因为我只是在运行单元测试。我通过将保存代码拉到另一个方法并在该方法上运行单元测试“解决”了这个问题,将render方法留给集成测试。
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'
    }