为什么我在单元测试中的域类之前*和之后*逻辑中收到“没有这样的属性”?

时间:2011-05-04 12:37:40

标签: unit-testing grails mocking grails-domain-class

我注意到在grails单元测试中需要域类时,缺少对属性的任何引用。

单元测试中的某处

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
    }
}

产生的错误

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 grails.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. 我如何才能创建有效的测试?
  2. 为什么堆栈跟踪表明它所声明的属性 缺少吗

1 个答案:

答案 0 :(得分:2)

您错误地将事件处理程序定义为静态闭包:

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

您无法在此处访问endDate,因为它(可能)是非静态属性。将您的事件处理程序更改为非静态,并且应该修复您的问题。

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