Asserting on a list of items in Spock
Asked Answered
S

1

7

Using Spock 0.7 with Grails 2.04. Trying to set up a testing environment. I need some help in regards to testing a list of objects.

I have a list of location objects. I want to test a date on each of those objects. I am iterating over but not sure how to make the test fail if the dates are not equal. Is there a good way to test objects in a list? I have listed below my then block of code.

then:
        weatherList != null
        weatherList.empty != null
        weatherList.size() == 3
        weatherList.each {
            Calendar today = Calendar.getInstance();
            today.clearTime()
            if(it.forecastDate != today) {
                return false
            }
        }
Schuck answered 30/10, 2012 at 12:15 Comment(0)
A
22

A solution could look like this (comments inlined):

// 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 }
Albin answered 30/10, 2012 at 12:57 Comment(2)
Thank you Peter, that was exactly what i was looking for. Do you mind clarify what you meant by avoid testing with real dates? Just setting up a testing environment and trying to get good sound practices in place.Schuck
As it stands now, the test might fail if it gets run around midnight. There might be a way to make it more reliable, for example by changing things so that you can test for a fixed day. Or maybe it's good enough to check that all list items have the same day.Albin

© 2022 - 2024 — McMap. All rights reserved.