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

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

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,, and the simple service,

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!