6

将 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
            }
        }
4

1 回答 1

22

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

// 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 }
于 2012-10-30T12:57:59.090 回答