5

当涉及到单元测试部分时,mongodb-1.1.0GA 的文档似乎已经过时:http: //springsource.github.com/grails-data-mapping/mongo/manual/ref/Testing/DatastoreUnitTestMixin.html

以下代码

@TestFor(Employee)
class EmployeeTests extends GroovyTestCase {

    void setUp() {
    }

    void tearDown() {
    }

    void testSomething() {
        mockDomain(Employee)

        def s = new Employee(firstName: "first name", lastName: "last Name", occupation: "whatever")
        s['testField'] = "testValue"
        s.save()

        assert s.id != null

        s = Employee.get(s.id)

        assert s != null
        assert s.firstName == "first name"
        assert s['testField'] == "testValue"

    }
}

失败并出现此错误:

No such property: testField for class: Employee

Employee 类非常简单:

class Employee {

    String firstName
    String lastName
    String occupation


    static constraints = {
        firstName blank: false, nullable: false
        lastName blank: false, nullable: false
        occupation blank: false, nullable: false
    }
}

那么,动态属性的单元测试是否可行?如果是,怎么做?

4

1 回答 1

4

动态属性没有开箱即用的支持,但添加起来相当容易。我已将以下代码放入我的设置方法中。它将动态属性添加到您使用@TestFor或启用的任何域类@Mock

grailsApplication.domainClasses.each { domainClass ->
    domainClass.metaClass.with {
        dynamicAttributes = [:]
        propertyMissing = { String name ->
            delegate.dynamicAttributes[name]
        }
        propertyMissing = { String name, value ->
            delegate.dynamicAttributes[name] = value
        }
    }
}
于 2013-04-09T14:55:06.950 回答