1

I have a Grails 2.2.4 project, and I'm trying to write a unit test for a method that queries over lastUpdated, like so:

Tile.createCriteria().list {
  lt('lastUpdated', new Date() - 1)
}

This method works fine in real life, but fails in my unit tests because I can't create any test data with lastUpdated other than now. Setting myTile.lastUpdated explicitly doesn't work, since that's an update and thus triggers the auto-timestamping. Turning off auto timestamping requires the eventTriggeringInterceptor, which doesn't seem to be available in unit tests. Mocking the default Date constructor to return other values was also no help. Direct SQL updates are not available in unit tests at all.

Is this possible in unit tests at all, or do I have to write an integration test?

David Seiler
  • 9,557
  • 2
  • 31
  • 39
  • Personally, I think if you're testing persistence, you should always favour an integration test, unless you've a very good reason not to. Running your persistence tests against a mock in-memory GORM implementation is just asking for trouble. – Dónal Oct 20 '16 at 10:10
  • That's fair, but I don't really want to test persistence, I want to test my query (which really is just about that simple). – David Seiler Oct 20 '16 at 11:45

1 Answers1

1

It's interesting that you say mocking the default date constructor to return other values is no help. I successfully do that quite often when I have queries such as yours that new up a date. For your situation, I would have a unit test that looked something like this:

def 'test lastUpdated query'() {
    setup:
    Title lessThan = new Title(lastUpdated:new Date(1477152000000)) //22 Oct 2016 16:00 UTC, should be found
    Title equalTo = new Title(lastUpdated:new Date(1477238400000)) //24 Oct 2016 16:00 UTC, should not find, not less than 1 day before, but equal to 1 day before
    Title notLessThan = new Title(lastUpdated:new Date(1477296000000)) //24 Oct 2016 08:00 UTC, should not find, not less than 1 day before
    Date date = new Date(1477324800000) //24 Oct 2016 16:00 UTC
    Date.metaClass.constructor = {-> return date}

    when:
    List<Title> result = service.someMethod()

    then:
    result.size() == 1
    result.contains(lessThan)
    !result.contains(equalTo)
    !result.contains(notLessThan)
}