开发者

Why do I receive "No such property" in before* and after* logic of domain classes in unit tests?

开发者 https://www.devze.com 2023-03-03 08:38 出处:网络
I notice that any reference to a property is missing when requiring domain classes in grails unit tests.

I notice that any reference to a property is missing when requiring domain classes in grails unit tests.

Somewhere in the Unit Test

mockDomain(Event)

10.times {
    e   = new Event(eventCalendar:ec, title:"$ec - Event $it", details:"some detail", location:"some location", startDate: now, endDate: now+1)
    e.save()
}

Event.groovy

static beforeInsert = {
    if (!endDate) {
        // do something about it
    }
}

Resulting error

No such property: endDate for class: myproj.Event Possible solutions: endDate

groovy.lang.MissingPropertyException: No such property: endDate for class: myproj.Event
Possible solutions: endDate
    at myproj.Event$__clinit__closure5.doCall(Event.groovy:74)
    at myproj.Event$__clinit__closure5.doCall(Event.groovy)
    at grai开发者_C百科ls.test.MockUtils.triggerEvent(MockUtils.groovy:724)
    at grails.test.MockUtils$_addDynamicInstanceMethods_closure68.doCall(MockUtils.groovy:752)
    at grails.test.MockUtils$_addDynamicInstanceMethods_closure68.doCall(MockUtils.groovy)
    at myproj.EventCalendarTest$_testCreateAndDeleteCalendarWithEvents_closure1.doCall(EventCalendarTest.groovy:43)
    at myproj.EventCalendarTest.testCreateAndDeleteCalendarWithEvents(EventCalendarTest.groovy:40)
  1. How can I still create a working test?
  2. Why is the stacktrace suggesting the property which it has stated as missing?


You've incorrectly defined your event handler as a static closure:

static beforeInsert = {
    if (!endDate) {
        // do something about it
    }
}

You can't access endDate here because it's (presumably) a non-static property. Change your event handler to be non-static and your problem should be fixed.

def beforeInsert = {
    if (!endDate) {
        // do something about it
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消