Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is unit testing of mongodb dynamic attributes possible in Grails 2.2?

It seems docs for mongodb-1.1.0GA are outdated when it comes to unit testing section: http://springsource.github.com/grails-data-mapping/mongo/manual/ref/Testing/DatastoreUnitTestMixin.html

Following code

@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"

    }
}

fails with this error:

No such property: testField for class: Employee

Employee class is pretty straightforward:

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

So, is unit testing of dynamic attributes possible? If it is, how?

like image 543
Krystian Avatar asked Oct 05 '22 01:10

Krystian


1 Answers

There's no out of the box support for dynamic attributes but it's fairly easy to add. I've put the following code in my setup method. It will add dynamic attributes to any domain classes you have enabled using @TestFor or @Mock.

grailsApplication.domainClasses.each { domainClass ->
    domainClass.metaClass.with {
        dynamicAttributes = [:]
        propertyMissing = { String name ->
            delegate.dynamicAttributes[name]
        }
        propertyMissing = { String name, value ->
            delegate.dynamicAttributes[name] = value
        }
    }
}
like image 96
Rob Fletcher Avatar answered Oct 13 '22 12:10

Rob Fletcher