You can make use of Hamcrest support in Spock and use the Matcher
designed explicitly for this case - containsInAnyOrder
. You need the following imports:
import static org.hamcrest.Matchers.containsInAnyOrder
import static spock.util.matcher.HamcrestSupport.that
Then you can write your test code as follows:
given:
def companyList = [ "Second", "First"]
expect:
that companyList, containsInAnyOrder("First", "Second")
This has the benefit over using .sort()
in that duplicate elements in the List will be considered correctly. The following test will fail using Hamcrest but passes using .sort()
given:
def companyList = [ "Second", "First", "Second"]
expect:
that companyList, containsInAnyOrder("First", "Second")
Condition not satisfied:
that companyList, containsInAnyOrder("First", "Second")
| |
| [Second, First, Second]
false
Expected: iterable over ["First", "Second"] in any order
but: Not matched: "Second"
If you're using then:
instead of expect:
you can use the expect
instead of that
import for readability.
then:
expect companyList, containsInAnyOrder("First", "Second")