How do I unit test a Grails service that uses a converter? How do I unit test a Grails service that uses a converter? json json

How do I unit test a Grails service that uses a converter?


Even though you are testing a service, you can apply the @TestMixin(ControllerUnitTestMixin) annotation to your test class to get Grails to set up the JSON converter.


The as JSON magic is created when the domain framework spins up.

You have to either change your test to an integration one or mock the asType.

def setUp(){    java.util.LinkedHashMap.metaClass.asType = { Class c ->        new grails.converters."$c"(delegate)    }}

Rember to clean up after yourself in the tearDown, you wouldn't want metaprogramming leaks in your test suite.

def tearDown(){    java.util.LinkedHashMap.metaClass.asType = null}

Edit:If you come from the future, consider this answer: https://stackoverflow.com/a/15485593/194932


As Grails 3.3.x grails-test-mixins plugin is deprecated. @see migration guide.

For this problem you should implement GrailsWebUnitTest which is coming from Grails Testing Support Framework.