2013-02-12 6 views
5

Es scheint docs für mongodb-1.1.0GA veraltet sind, wenn es um Abschnitt Unit-Tests kommt: http://springsource.github.com/grails-data-mapping/mongo/manual/ref/Testing/DatastoreUnitTestMixin.htmlIst in Grails 2.2 Unit-Tests von dynamischen mongodb-Attributen möglich?

Code Nach

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

    } 
} 

mit diesem Fehler fehlschlägt:

No such property: testField for class: Employee 

Employee-Klasse ist ziemlich einfach:

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

Ist das Komponententest dynamischer Attribute möglich? Wenn es ist, wie?

Antwort

4

Es gibt keine Out-of-the-Box-Unterstützung für dynamische Attribute, aber es ist ziemlich einfach hinzuzufügen. Ich habe den folgenden Code in meine Setup-Methode eingefügt. Es fügt allen Domänenklassen, die Sie mit @TestFor oder @Mock aktiviert haben, dynamische Attribute hinzu.

grailsApplication.domainClasses.each { domainClass -> 
    domainClass.metaClass.with { 
     dynamicAttributes = [:] 
     propertyMissing = { String name -> 
      delegate.dynamicAttributes[name] 
     } 
     propertyMissing = { String name, value -> 
      delegate.dynamicAttributes[name] = value 
     } 
    } 
} 
+0

Erstellt es etwas, das statisch ist? Ich bekomme den gleichen Wert für alle Artikel, wenn ich es für eins setze! –

+0

Ja, mein Fehler. Verwenden Sie eine 'for' Schleife mit do that (ich habe darüber geblogged warum hier http://blog.freeside.co/2013/03/29/groovy-gotcha-for-loops-and-closure-scope/) Ich werde aktualisieren die Antwort –

+0

Ich habe deine Antwort bearbeitet !, das hat für mich funktioniert! Fühlen Sie sich frei, meine Antwort zu genehmigen oder abzulehnen! Und ich denke du verbesserst dein Blog auch! –