Search

Dark theme | Light theme

May 7, 2010

Grails Goodness: Using Codecs in Test Classes

When we run Grails a lot of metaClass information is added to the classes of our application. This also include the support for encoding and decoding String values. For example in our Grails application we can use "<b>Grails</b>".encodeAsHTML() and we get "&lt;b&gt;Grails&lt;/b&gt;". But if we want to use the encodeAsHTML() method in our class we get an exception, because the method is not available. To make a Grails encoder/decoder available in our test class we must use the loadCodec() method. See the following example:

package com.mrhaki.grails

class HTMLCodecControllerTests extends grails.test.ControllerUnitTestCase {
    void testAction() {
        loadCodec HTMLCodec  // Now we can use encodeAsHTML, decodeAsHTML
        assertEquals "&lt;b&gt;Grails&lt;/b&gt;", '<b>Grails</b>'.encodeAsHTML()
    }
}