I have a list of some objects - let's assume companies. Now I want to check if this list contains companies with some names but not taking order into consideration. Currently I'm using such construction:
companyList.name.sort() == ["First", "Second"]
Is there any operator in Spock or Groovy that allows me to compare arrays without order?
There's no such operator as far as I know. If the list doesn't contain any duplicates the following assertion may be used:
companyList.name as Set == ["First", "Second"] as Set
Or something like that:
companyList.name.size() == ["First", "Second"].size() && companyList.name.containsAll(["First", "Second"])
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With