Load codecs in Unit tests using Groovy Grails
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
Awesome blog.Much thanks again. Really Cool.
Muchos Gracias for your blog.Really looking forward to read more. Will read on…
Thank you for your article.Much thanks again. Much obliged.
wow, awesome article.Really looking forward to read more.
With grails 2.3.0, mockCodec(UrlCodec) works too. Thanks
Salil,
thanks for the tip, it helps.