16 October 2013

Mocking grailsApplication

You don't have to mock grailsApplication, unless you've put yourself  in the same boat as me and like writing pure jUnit. Keep running grails test-app all the time is just annoying and slow. Note I havent tested Grails 2.3 yet, which is supposed to be faster than the predecessors.

Anyway. This "pure" approach has one downside: your service/controller aren't getting its dependencies injected for free. You have to do everything yourself.

Injecting services is easy, as you just @grails.test.mixin.Mock them in during setUp(). But there is that def grailsApplication sitting at the top of your file. How to best mock it so you don't get NullPointerException in your test? I (mostly) use grailsApplication for configuration, so there lies my need for mocking.

There are several ways of getting this done and I have two ways which I use. I can't decide on a favorite. Here they are, I'll let you decide what you like:

nested maps

public void setUp() {
  service = MyService() //service is a global variable for the entire test.
  service.grailsApplication = [config:[myApp:[jms:[firstQueue:"firstQueue"]]]]

This works best if you have really few properties. Maybe just one. But it's a one-liner, which I like.


public void setUp() {
  service = MyService()
  def mockConfig = new ConfigObject()
  service.grailsApplication = [config: mockConfig]

I know deep down that ConfigObject is the proper way of doing this - but it's more stuff to write.

Which do you like best?

No comments:

Post a Comment