【问题标题】:Cannot persist an entity within an integration test using the MongoDB GORM plugin无法使用 MongoDB GORM 插件在集成测试中持久化实体
【发布时间】:2014-09-03 17:46:41
【问题描述】:

上下文: 我创建了一个名为 AppDomain 的新插件,其中包含 Mongo 3.0.1 插件。它有一个领域类(Person)和一个集成测试(PersonSpec)。

问题: 正在生成 ID。正在 Mongo 中创建 appdomain 数据库和人员集合。但是,集成测试在收集计数方面失败。

注意事项: 在查阅了我能找到的所有文档并对生成的 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
    }
}

【问题讨论】:

  • 使用 findAll() 或 getAll() 代替 list() 是否得到相同的结果?
  • 我做@ÖzgürEroğlu。 findAll() 和 getAll() 以同样的方式失败。和 Person.count() 一样。
  • @JasonStonebraker,也许您在配置测试环境中有一些不正确的数据库选项?例如,您的数据库未创建且dbCreate = "validate" 或不存在。我认为与 mongo 必须存在类似的偏好。

标签: mongodb grails grails-plugin gorm-mongodb


【解决方案1】:

GORM 并不总是在您调用 save 后立即持久化对象。

Official Reference

save 方法通知持久化上下文一个实例 应该保存或更新。对象不会被持久化 除非使用了 flush 参数,否则立即。

因此,您应该调用 save 立即刷新会话,以便更改立即生效。

. . .
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页面了解更多关于保存方法的信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 2015-11-15
    • 2017-04-27
    • 2016-01-23
    相关资源
    最近更新 更多