Archer
Archer

Reputation: 5147

Controller under unit test return empty contentAsString

have some controller with:

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

Also have unit test:

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

Second assertion fails, as contentAsString return "". When I replace my render() with render("html") - contentAsString is fulfilled even under test. What I'm doing wrong?

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

UPDATE 2 Upgrade from grails 2.2.3 to grails 2.2.4 does not help ;(

Upvotes: 0

Views: 384

Answers (1)

user800014
user800014

Reputation:

Ok, I revisited the Unit Testing section of docs. It seems that the response.contentAsString can be used only when you render your text directly. For rendering a view, you can check the item "Testing View Rendering" of the docs.

Example:

// 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"
}

Upvotes: 2

Related Questions