EDIT: Please let me be clear, I’m asking how to do this in Grails using Spring Dependency Injection, and NOT Grails’ metaclass functionality or new().
I have a grails service that is for analyzing log files. Inside the service I use the current time for lots of things. For unit testing I have several example log files that I parse with this service. These have times in them obviously.
I want my service, DURING UNIT TESTING to think that the current time is no more than a few hours after the last logging statement in my example log files.
So, I’m willing to this:
class MyService {
def currentDate = { -> new Date() }
def doSomeStuff() {
// need to know when is "right now"
Date now = currentDate()
}
}
So, what I want to be able to do is have currentDate injected or set to be some other HARDCODED time, like
currentDate = { -> new Date(1308619647140) }
Is there not a way to do this with some mockWhatever method inside my unit test? This kind of stuff was super easy with Google Guice, but I have no idea how to do it in Spring.
It’s pretty frustrating that when I Google “grails dependency injection” all I find are examples of
class SomeController {
// wow look how amazing this is, it's injected automatically!!
// isn't spring incredible OMG!
def myService
}
It feels like all that’s showing me is that I don’t have to type new …()
Where do I tell it that when environment equals test, then do this:
currentDate = { -> new Date(1308619647140) }
Am I just stuck setting this property manually in my test??
I would prefer not to have to create a “timeService” because this seems silly considering I just want 1 tiny change.
Thanks for the help guys. The best solution I could come up with for using Spring DI in this case was to do the following in
resources.groovyThese are the two solutions I found:
1: If I want the timeNowService to be swapped for testing purposes everywhere:
2: I could do this if I only want this change to apply to this particular service:
In either case I would use the service by calling
timeNowService.now().The one strange, and very frustrating thing to me was that I could not do this:
In fact, when I tried that I also had a dummy value in there, like
dummy = 'hello 2'and then a default value ofdummy = 'hello'in the myService class itself. And when I did this 3rd example with the dummy value set in there as well, it silently failed to set, apparently b/c timeNow blew something up in private.I would be interested to know if anyone could explain why this fails.
Thanks for the help guys and sorry to be impatient…