简体   繁体   中英

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

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.

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

static doWithSpring = { grailsTagDateHelper(DefaultGrailsTagDateHelper) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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