Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array assertion in Spock

Tags:

groovy

spock

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?

like image 495
Jakub Kubrynski Avatar asked Feb 11 '15 10:02

Jakub Kubrynski


2 Answers

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"])
like image 86
Opal Avatar answered Oct 12 '22 22:10

Opal


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")
like image 37
tddmonkey Avatar answered Oct 12 '22 23:10

tddmonkey