title: Grails 4: How to test code that depend on Converters (like "as JSON")
body: <p>How to write a test (functional, unit, integration) to test a class that contains a Grails converter(s)? At the minimum I should be able to write a working integration test.</p>
  
  <p>Example: The following line works fine outside of the test scope, but fails in both unit-tests and integration tests:</p>
  
  <pre><code>def json= "{}" as JSON
  </code></pre>
  
  <p>with <code>GroovyCastException: Cannot cast object '{}' with class 'java.lang.String' to class 'grails.converters.JSON'</code>. The expected outcome is that a <code>JSON</code> type is returned.</p>
  
  <p>There seems to be the same problem with earlier versions in <a href="https://github.com/grails/grails-core/issues/3660" rel="nofollow noreferrer">GRAILS-4715</a>, however its been closed so I assume it was fixed. In Grails 3.X this issue could be circumvented like this <a href="https://stackoverflow.com/questions/11785708/how-do-i-unit-test-a-grails-service-that-uses-a-converter/15485593#15485593">How do I unit test a Grails service that uses a converter?</a>. However, none of the presented workarounds seem to work in Grails 4.X. I tried manually enabling and registering the converters in the same manner it was done in Grails 3 with <code>@TestMixin</code>, but this was a dead end for me.</p>
  
  <p>Using Grails version 4.0.3. </p>
  
  <p>I also opened I ticket for this towards the Grails project <a href="https://github.com/grails/grails-core/issues/11521" rel="nofollow noreferrer">https://github.com/grails/grails-core/issues/11521</a> hoping for a long term solution to the problem or at least some documentation on how to test this common use case of Grails converters.</p>