5

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?

Krystian
  • 3,193
  • 2
  • 33
  • 71

1 Answers1

4

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
        }
    }
}
Rob Fletcher
  • 8,317
  • 4
  • 31
  • 40
  • Does it create something that is static? I get the same value for all items if i set it for one! – Amanuel Nega Dec 05 '14 at 07:54
  • Yep my mistake. Using a `for` loop with do that (I blogged about why here http://blog.freeside.co/2013/03/29/groovy-gotcha-for-loops-and-closure-scope/) I'll update the answer – Rob Fletcher Dec 07 '14 at 01:48
  • I've edited your answer!, that worked for me! Feel free to approve or reject my answer! And i think u better update ur blog too! – Amanuel Nega Dec 08 '14 at 06:44
  • I don't understand. I edited it already & the blog contains the right information. – Rob Fletcher Dec 08 '14 at 15:01
  • This particular solution doesn't work! when one instance is changed the all the instances of that domain class are changed! Here see my question and also my solution: http://stackoverflow.com/questions/27312245/metaclass-deligate-not-being-instance – Amanuel Nega Dec 08 '14 at 15:45
  • It doesn't work when it uses a `for` loop (which I had in my original answer) but it does when using `each`. – Rob Fletcher Dec 09 '14 at 20:48