【问题标题】:unit testing the unique constraint on domain class单元测试域类的唯一约束
【发布时间】:2014-06-24 19:15:38
【问题描述】:

我正在使用 Grails 2.4.1,但无法理解如何正确测试域类的唯一约束。

我的域类看起来像: 类人{

    String name
    static constraints = {
        name( unique: true, blank: false )
    }
}

和我的测试:

@TestFor(Person)
@TestMixin(GrailsUnitTestMixin)
class PersonSpec extends Specification {

void "name should be unique"() {
    given:
    mockForConstraintsTests Person

    when:
    def one = new Person( name: 'john' )

    then:
    one.save()

    when:
    def two = new Person( name: 'john' )

    then:
    ! two.validate()
    two.errors.hasFieldErrors( 'name' )

}

尽管显然违反了唯一性约束,但第二个实例仍在验证中。有人可以解释一下这里发生了什么以及我应该如何最好地纠正它吗?

谢谢!

--约翰

【问题讨论】:

  • 您可以尝试将 2 组 when then 组合在一起。您也可以尝试进行冲洗作为保存的一部分。 one.save(flush:true)
  • 谢谢乔。看起来我也可以只刷新第一个实例,即“one.save(flush: true)”
  • 您也可以将初始数据传递给 mockForConstraintsTests 方法,例如mockForConstraintsTests(Person, [new Person(name: 'john')])
  • 自从您使用 Grails 2.4 后,您就有了使用 HibernateTestMixin 的新可能性。它允许您在单元测试中完全集成 Hibernate。您不需要模拟您的域类。见grails.org/doc/latest/guide/introduction.html#whatsNew24

标签: unit-testing grails


【解决方案1】:

我认为通过触发约束来测试约束并不是最好的方法。 通常我们想要测试我们的代码是否正常工作,而不是 Grails 正在验证约束。

为什么要测试框架(即 Grails)?希望 Grails 的人已经做到了 :-) (是的,在某些情况下检查框架是有意义的,但我不认为这是一个)。

所以唯一要测试的是我们在域类上放置了正确的约束:

@TestFor(Person)
class PersonSpec extends Specification {

    void "name should have unique/blank constraints"() {
        expect:
        Person.constraints.name.getAppliedConstraint('unique').parameter
        ! Person.constraints.name.getAppliedConstraint('blank').blank
    }
}

如果值得写那个测试是另一个问题......

【讨论】:

    【解决方案2】:

    这正是我作为初学者常犯的错误。测试 grails 的东西是否按预期工作。测试框架相关的东西不是一个好主意。这意味着然后测试所有约束、预定义方法,甚至 save()、update() 等。所以这意味着再次测试 grails 框架而不是开发您的应用程序。

    测试通常应该包括测试你的业务逻辑相关的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-26
      • 2021-04-08
      • 2019-09-23
      相关资源
      最近更新 更多