Monday, January 17, 2011

"as Whatever" is Essential When Doing Groovy Map Coercion

It's helpful to always use the "as" operator when using Map Coercion in Grails (which uses Groovy).
To understand Map Coercion, one should read an article such as http://docs.codehaus.org/display/GROOVY/Groovy+Mocks

While creating unit tests and mocking, one needs to be careful to always use the "as" operator. Example:
Here's a test (located at https://gist.github.com/783407 )

class SomethingTests extends GrailsUnitTestCase {

    void testSomething() {
        Something thing = new Something()
        // thing.someService = [ get : { a -> throw new Throwable() } ]  as SomeService // works
        thing.someService = [ get : { a -> throw new Throwable() } ] // need the "as" operator!

        assert thing.methodWeAreTesting()
    }
}

For completeness, here's the system under test, https://gist.github.com/783412, and the simple service, https://gist.github.com/783419.

If you do not use the "as" operator, you end up with a service that is a java.util.LinkedHashMap as opposed to a groovy proxy object (SomeService_groovyProxy). When the code calls 'get', it does not execute the mock "get" code that was set up! Instead you get back a value or null.

So remember to use the "as" operator such as " as SomeService "

Happy coding!