1

I cannot query domain classes in unit tests that use a field of type LocalDate.

I am trying to persist date and time values like LocalDate which were introduced in Java 8. Grails 3.1.1 and Gorm 5 are the stack. I already followed How to configure Grails 3.1.1 to use Hibernate 5 to make use of Hibernate 5.

I added compile "org.hibernate:hibernate-java8:5.0.7.Final" for the new type mappings of the date and time api. That works fine when running the app. Persist and load are possible.

Unit tests on the other hand crash. For example take this domain class:

class Event {
    String name
    LocalDate date
}

And this unit test:

void "test criteria with date"() {
    when:
    def c = Event.createCriteria()
    c.list {
        eq("date", LocalDate.now())
    }.each {
        println it
    }
    then:
    true
}

It crashes with this:

java.lang.IllegalArgumentException: Property [date] is not a valid property of class [localdate.Event]
at grails.gorm.CriteriaBuilder.validatePropertyName(CriteriaBuilder.java:1132)
at grails.gorm.CriteriaBuilder.eq(CriteriaBuilder.java:489)
at localdate.EventControllerSpec.test criteria with date_closure2(EventControllerSpec.groovy:31)
at localdate.EventControllerSpec.test criteria with date_closure2(EventControllerSpec.groovy)
at groovy.lang.Closure.call(Closure.java:426)
at groovy.lang.Closure.call(Closure.java:420)
at grails.gorm.CriteriaBuilder.invokeClosureNode(CriteriaBuilder.java:1157)
at grails.gorm.CriteriaBuilder.list(CriteriaBuilder.java:279)
at grails.gorm.CriteriaBuilder.list(CriteriaBuilder.java:52)
at localdate.EventControllerSpec.test criteria with date(EventControllerSpec.groovy:30)

My guess is that the new types are not available while testing as a unit test. On the other hand, the test works if it is done as an integration test.

I do not want to be forced to test all controller logic in integration tests. How to make the domain classes unit testable again?

Community
  • 1
  • 1
Robert Kühne
  • 898
  • 1
  • 12
  • 33

1 Answers1

0

The HibernateTestMixin as described in https://grails.github.io/grails-doc/latest/guide/testing.html#unitTestingDomains solved the problem. In the example given above I added:

@Domain(Event)
@TestMixin(HibernateTestMixin)

You also need an extra dependency:

testCompile 'org.grails:grails-datastore-test-support:5.0.1.RELEASE'
Robert Kühne
  • 898
  • 1
  • 12
  • 33