【问题标题】:Asserting on a list of items in Spock在 Spock 中的项目列表上断言
【发布时间】:2012-10-19 18:42:10
【问题描述】:

将 Spock 0.7 与 Grails 2.04 一起使用。尝试搭建测试环境。我需要一些关于测试对象列表的帮助。

我有一个位置对象列表。我想测试每个对象的日期。我正在迭代但不确定如果日期不相等如何使测试失败。有没有一种测试列表中对象的好方法?我在下面列出了我当时的代码块。

then:
        weatherList != null
        weatherList.empty != null
        weatherList.size() == 3
        weatherList.each {
            Calendar today = Calendar.getInstance();
            today.clearTime()
            if(it.forecastDate != today) {
                return false
            }
        }

【问题讨论】:

    标签: grails-2.0 spock


    【解决方案1】:

    解决方案可能如下所示(cmets 内联):

    // avoid testing with real dates if possible
    def today = Calendar.getInstance().clearTime() 
    
    when:
    ...
    
    then:
    weatherList != null
    weatherList.size() == 3
    // does this list really contain Calendar objects?
    weatherList.every { it.forecastDate == today }
    // OR, for a potentially better error message
    weatherList.each { assert it.forecastDate == today }
    

    【讨论】:

    • 谢谢彼得,这正是我想要的。您介意澄清一下避免使用真实日期进行测试的意思吗?只需设置一个测试环境并尝试建立良好的良好实践。
    • 就目前而言,如果在午夜左右运行测试可能会失败。可能有一种方法可以使其更可靠,例如通过更改某些内容以便您可以在固定的日期进行测试。或者,检查所有列表项是否具有同一天就足够了。
    猜你喜欢
    • 1970-01-01
    • 2019-01-19
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多