mongodb - 无法使用 MongoDB GORM 插件在集成测试中保留实体

标签 mongodb grails grails-plugin gorm-mongodb

上下文: 我创建了一个名为 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 并不总是在您调用保存后立即保留对象。

Official Reference

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/

相关文章:

spring - 如何解决 grails bootstrap 执行错误 "postProcessBeanDefinitionRegistry already called for this post-processor"?

java.lang.NoSuchMethodError 通过 Spring 连接 mongoDb 时出错

mongodb - 删除除最新文档之外的所有重复项

grails - jboss中不同 war 模块之间的 session 共享?

grails - (未保存的)groovy 中多对多关系中的数据

grails - 大气 meteor 和 meteor 一样吗

mongodb - 如何从 MongoDB 聚合中的不同集合添加多个 $match 条件

python - 如何为我的 pymongo/twitter 脚本创建函数?

grails - 在Groovy Controller /服务中使用非默认dataSource

email - Grails 邮件插件在开发模式下传送到控制台/日志