Load codecs in Unit tests using Groovy Grails

23 / Feb / 2011 by Salil 6 comments

This post is all about enabling codecs (like encodeAsURL, decodeURL, etc) in your Grails Unit tests. I am assuming that you are already familiar with writing unit tests.

Scenario:
In our application code, if we have something like below:
[groovy]
String serviceUrl = "http://example.com/service"
String username = "usernameStr"
String password = "passwordvalue"
String urlStr = "${serviceUrl}?u=${username.encodeAsURL()}&p=${password.encodeAsURL()}.."
[/groovy]
Above code works very well when we run the application or even Integration tests. As we know that Codecs are automatically injected by Grails when application starts up.

Problem:
When we use this code in our Unit Tests, it won’t work. Reason, Unit tests do not load Grails specific environment automatically. We have to mock or load the things (whatever required by test).

Solution:
GrailsUnitTestCase class provides a method loadCodec(CodecClass). So here, to make encodeAsURL() working in our Unit tests, we just need add following line of code in our test (setup method).
[groovy]
loadCodec(URLCodec)
[/groovy]

That’s it. Rest of the work will be taken care by Grails 🙂

So whatever codec you need to load, just invoke loadCodec method with required codecClass in argument.

Your comments are always Welcome. Please post if you have any!

Cheers!
Salil Kalia
Salil [at] IntelliGrape [dot] com
Twitter LinkedIn

FOUND THIS USEFUL? SHARE IT

comments (6)

Leave a Reply

Your email address will not be published. Required fields are marked *