【问题标题】:Controller under unit test return empty contentAsString单元测试下的控制器返回空 contentAsString
【发布时间】:2013-08-27 11:32:18
【问题描述】:

有一些控制器:

  def index() {
    ...
    render(view: 'index', model: [exceptions: exceptions]                                                                                         
    }        

还有单元测试:

  def testIndex(){
    ...
    controller.index()
    assert controller.response.status == 200
    assert controller.response.contentAsString != ""
  }

第二个断言失败,contentAsString 返回 ""。当我用render("html") 替换我的render() 时,即使在测试中,contentAsString 也会得到满足。我做错了什么?

更新 1

index.gsp

<%@ page contentType="text/html"%>
<%@ page import="org.apache.commons.lang.exception.ExceptionUtils" %>
<html>
<head>
<title>Exceptions catched during crawling</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script type="text/javascript">
  $(function(){
     $(".stacktrace").hide()
     $("a").click(function(){
       $(this).parents("li").siblings("pre").toggle()
   return false;
     })
  })
</script>
</head>
<body>
<g:each var="entry" in="${exceptions.entrySet()}">
  Catched <b>${entry.key.name}</b> for these URLs:                                                                                                                                                                                         
  <ol>
    <g:each var="ex" in="${entry.value.entrySet()}">
      <li><a href="${ex.key}">${ex.key}</a>: ${ex.value.message}</li>
        <pre class="stacktrace">
          ${ExceptionUtils.getStackTrace(ex.value)}
        </pre>
</g:each>
  </ol>
</g:each>
</body>
</html>

更新 2 从 grails 2.2.3 升级到 grails 2.2.4 没有帮助;(

【问题讨论】:

  • 一般我都是response.text,你可以试试吗?
  • 试过了。 response.text 也不起作用。
  • 你的 index.gsp 中有什么?
  • index.gsp 已列出。我在run-app 下工作得很好。仅在test-app unit:下不工作

标签: unit-testing grails controllers


【解决方案1】:

好的,我重新访问了文档的 Unit Testing 部分。 response.contentAsString 似乎只能在您直接渲染文本时使用。对于渲染视图,您可以检查文档的“测试视图渲染”项。

例子:

// Test class
class SimpleController {
    def home() {
        render view: "homePage", model: [title: "Hello World"]
    }
    …
}

void testIndex() {
    controller.home()
    assert view == "/simple/homePage"
    assert model.title == "Hello World"
}

【讨论】:

  • 如何访问呈现的 HTML 内容?
  • @archer 在这种情况下,没有生成 html 内容。请参阅邮件列表中的Jeff's response
  • 如果你真的需要测试 html,那么你需要得到这个 ModelAndView 并执行类似 this post 的操作。
  • 是的,谢谢。但是在单元测试中它没有被初始化。将尝试转向集成并查看
  • 即使在生产中也不适合我。由于某种原因,模型数据不能从 gsp 内部获得。可能它不能从控制器中使用,应该在那里使用默认的渲染方法?
猜你喜欢
  • 2022-07-27
  • 2017-05-08
  • 2023-03-15
  • 2020-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-11
  • 1970-01-01
相关资源
最近更新 更多