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