上下文: 我创建了一个名为 AppDomain 的新插件,其中包含 Mongo 3.0.1 插件。它有一个领域类(Person)和一个集成测试(PersonSpec)。
问题: 正在生成 id。 appdomain 数据库和人员集合正在 Mongo 中创建。但是,集成测试在集合计数上失败。
注意事项: 在查阅了我能找到的所有文档并对生成的 AppDomain 插件代码进行了最低限度的更改之后,我不知道为什么此处包含的持久性测试失败了。我有一个使用 junit 测试使用 grails 2.2.2 配置的类似插件,效果很好。
感谢任何帮助。
package appdomain
class Person {
String firstName
String lastName
}
-
package appdomain
import grails.test.mixin.TestMixin
import grails.test.mixin.mongodb.*
import spock.lang.*
@TestMixin(MongoDbTestMixin)
class PersonSpec extends Specification {
def setup() {
}
def cleanup() {
}
void "can persist a person to the appdomain mongo database"() {
given: "a person"
def aPerson = new Person(firstName: "Homer", lastName: "Simpson")
when: "the person is saved"
aPerson.save()
then: "the person has an id"
aPerson.id != null //Passes
and: "the Person collection contains one item"
Person.list().size() == 1 //Fails with Person.list().size() == 0
}
}
最佳答案
GORM 并不总是在您调用保存后立即保留对象。
The save method informs the persistence context that an instance should be saved or updated. The object will not be persisted immediately unless the flush argument is used.
因此,您应该立即调用 save 刷新 session ,以便更改立即生效。
. . .
when: "the person is saved"
aPerson.save(flush:true)
. . .
有时,由于验证或其他非常见错误,保存会失败(即使提供了 flush:true
)!如果您想在这些情况下获得异常,您还应该像这样添加 failOnError:true
. . .
when: "the person is saved"
aPerson.save(flush:true, failOnError:true)
. . .
在 Official Reference 中阅读有关保存方法的更多信息页
关于mongodb - 无法使用 MongoDB GORM 插件在集成测试中保留实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24725881/