Tuesday, December 27, 2011

Basic Grails custom tag testing errors

You may encounter an error such as the following:

"No such property: out<or other method name> in package.classname "


This comes from writing the taglibtest like all the tutorials out on the web had said to, e.g. using:

class DateTagLib {
def thisYear = {
out << Calendar.getInstance().get(Calendar.YEAR)
'' //return empty text
 }
}

This problem arises from the newer versions of grails producing UNIT tests rather than INTEGRATION tests. In the unit environment, the Grails engine is not active to inject the dynamically created methods, such as validate, out.

So how do I resolve this? It runs just fine on the test webpage its included on. The test was failing when the tag clearly worked.



Three things to fix:

  1. Make sure your test case is extending TagLibUnitTestCase.
  2. Make sure you are calling super.setUp() in your test constructor
  3. Make a call to mockTagLib(YourTagClassHere) at the beginning of your test method.


So a basic test case for a custom tag (as shown above) might look like the following:


package yourpackage
import grails.test.*
class DateTagLibTests extends TagLibUnitTestCase  {
  def dateTagLib


  void setUp(){
 super.setUp()
 
    dateTagLib = new DateTagLib()

  }


  void testThisYear() {
 mockTagLib(DateTagLib)
    String expected = Calendar.getInstance().get(Calendar.YEAR)
    assertEquals("the years don't match", expected, dateTagLib.thisYear().toString())
  }
}

No comments:

Post a Comment