Search code examples
javagroovyspock

Assert two lists are equal in Spock framework


I test my application using Spock framework, the tests are written in Groovy.

As a result of some method evaluation I have a list of objects. I want to test if this list is the same as the list I expect. I have coded the following:

def expectedResults = [ ... ] //the list I expect to see
def isEqual = true;

when:
def realResults = getRealResultsMethod() //get real results in a list here
expectedResults.each {isEqual &= realResults.contains(it)}
then:
isEqual
0 * errorHandler.handleError(_) //by the way assert that my errorHandler is never called

This is one of my first experiences with Groovy, so may be I am missing something?

PS

What confuses me is 'equals' operator in Groovy and Spock. Given Java ArrayList or Java array, equals operator is simply identity operator: equals is ==. In Groovy as far as I understand default equals operator is really equals (form here: http://groovy.codehaus.org/Differences+from+Java). But what is 'equals' for Groovy List or Set?

UPDATE

To be more precise. I want to find out wether the two lists have the same objects, no extra objects for both list, the order doesn't matter. For example:

list=[1,5,8]

list1=[5,1,8]    
list2=[1,5,8,9]

println(list == list1) //should be equal, if we use == not equal    
println(list == list2) //should not be equal, if we use == not equal

Solution

  • Just do:

    when:
        def expectedResults = [ ... ]
        def realResults = getRealResultsMethod()
    
    then:
        realResults == expectedResults
    

    Or, if you don't care about order (which is breaking the contract of List, but there you go), you could do:

    then:
        realResults.sort() == expectedResults.sort()
    

    Or convert them to sets or something