Grails:AddTo出了问题

时间:2016-12-01 01:44:19

标签: grails grails-domain-class

我试图向自己证明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)

1 个答案:

答案 0 :(得分:1)

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

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