Grails:AddTo 的问题
Grails: trouble with AddTo
我试图向自己证明 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...
}
我试图向自己证明 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...
}