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

孤街醉人 提交于 2019-12-13 17:58:10

问题


I'm having a problem unit testing my controller method.

@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())
}

The problem comes when it tries to render the template.

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

It throws the following error:

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

When I step through the code in debugger mode, the date is definitely populated, and my actual app works just fine. It's just this unit test that is failing.

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'
    }

I'm just having trouble trying to wrap my head around what the problem could be. Especially as I know that the date object of the comment is definitely there and has the time zone.


回答1:


To solve this problem use code below in your static block of the groovy file:

static doWithSpring = { grailsTagDateHelper(DefaultGrailsTagDateHelper) }



来源:https://stackoverflow.com/questions/41103842/grails-cannot-invoke-gettimezone-on-null-object-during-unit-testing-of-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!