我试图向自己证明addTo将同时保存添加的域对象及其父对象,并在父对象上进行保存。我构造了这个简单的测试:

package testapp

import grails.test.mixin.TestFor
import spock.lang.Specification

/**
 * See the API for {@link grails.test.mixin.domain.DomainClassUnitTestMixin} for usage instructions
 */
@TestFor(Person)
class PersonSpec extends Specification {

    def setup() {
    }


    def cleanup() {
    }

    void "test PersonCreation"() {
        when: "create a person with a hobby"
        Hobby h = new Hobby(name: "Fishing")
        Person p = new Person()
        p.first="Sam"
        p.last="Parker"
        p.age = 30
        p.addToHobby(h)
        p.save()
        then: "Hobby is saved as well"
        Hobby.count() == 1
    }
}

但是,运行它会在p.addToHobby(h)处产生此错误
线:
java.lang.NullPointerException
    at org.grails.datastore.gorm.GormEntity$Trait$Helper.addTo(GormEntity.groovy:350)
    at testapp.PersonSpec.test PersonCreation(PersonSpec.groovy:27)


Process finished with exit code 255

域类非常简单:

人:
package testapp

class Person {

  String first
  String last
  Integer age

  static hasMany = [hobby: Hobby]

  static constraints = {}
}

爱好:
class Hobby {
    String name
    static constraints = {}
    static belongsTo = [person: Person]

}

我试过清理和重新编译,没有任何变化。 (Grails版本3.2.2)

最佳答案

您需要为Person和Hobby提供@Mock批注。这会将动态方法(如addTo)添加到域类中。

@Mock([Person, Hobby])
class PersonSpec extends Specification {
    ...your test code...
}

07-28 00:29