【问题标题】:How to avoid null field errors in spock for Grails domain mock如何避免 Grails 域模拟的 spock 中的空字段错误
【发布时间】:2013-02-19 11:45:37
【问题描述】:

在这个简单的域中使用 grails 2.2.0

class Order {
    static mapping = {table "ticket_order"}

    String foo
}

以及相关的spock测试

@TestFor(Order)
class OrderSpec extends Specification {
def "sensible constraints for order class"() {
    setup:
      mockForConstraintsTests(Order)

      when:
      def order = new Order(
        foo : foo
      )
      order.validate()

      then:
        !order.errors.hasFieldErrors("foo")

      where:
        foo = "bar"

}
}

我得到这个输出

grails> test-app unit: Order -echoOut
| Running 1 spock test... 1 of 1
--Output from sensible constraints for order class--
| Failure:  sensible constraints for order class(uk.co.seoss.presscm.OrderSpec)
|  Condition not satisfied:

!order.errors.hasFieldErrors("foo")
||     |      |
||     |      true
||     org.codehaus.groovy.grails.plugins.testing.GrailsMockErrors: 1 errors
||     Field error in object 'uk.co.seoss.presscm.Order' on field 'foo': rejected value [null];

有人可以解释为什么我得到那个空值,我没有正确设置属性吗?我已经尝试了一些更简单的公式,但没有任何乐趣。它在标准单元测试中运行良好。

【问题讨论】:

  • 您尝试过简单的 JUnit 测试吗?我最好的猜测是问题与 Spock 无关。

标签: grails spock


【解决方案1】:

在我看来,您混合了数据驱动和基于交互的测试风格。 where 块仅在数据驱动的上下文中被提及,而 when/then 组合则在交互测试的上下文中被提及。

尝试将 def foo = "bar" 放在测试的顶部。

【讨论】:

  • when-then 可用于任何测试(不仅仅是基于交互的),它与where 一起工作得很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 2015-05-25
  • 1970-01-01
  • 2022-06-16
  • 1970-01-01
相关资源
最近更新 更多