Spock Array Approval

I have a list of some objects - let the companies accept. Now I want to check if this list contains companies with names, but does not take into account the order. I am currently using this construct:

companyList.name.sort() == ["First", "Second"]

Is there any operator in Spock or Groovy that allows me to compare arrays without ordering?

+6
source share
3 answers

There is no such operator, as far as I know. If the list does not contain duplicates, you can use the following statement:

 companyList.name as Set == ["First", "Second"] as Set 

Or something like that:

 companyList.name.size() == ["First", "Second"].size() && companyList.name.containsAll(["First", "Second"]) 
+12
source

You can use Spock's Hamcrest support and use Matcher 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 advantage over using .sort() in that duplicate items in the List are considered correctly. The following test will not work using Hamcrest, but will pass 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 use then: instead of expect: you can use expect instead of that to read to read.

 then: expect companyList, containsInAnyOrder("First", "Second") 
+7
source

Acquired for @Opal's answer, it is probably the best in all terms. As a curiosity, I would add only an example of using the minus operator to compare two unsorted lists:

 import spock.lang.Specification class ComparingListsSpec extends Specification { def "should contain all companies in two unsorted lists"() { when: def companies = ["Lorem", "ipsum", "dolor", "sit", "amet"] def unsorted = ["ipsum", "sit", "Lorem", "dolor", "amet"] then: companies - unsorted == [] and: unsorted - companies == [] and: companies - unsorted in [[]] } } 

It also works if one of the lists contains redundant data.

+1
source

Source: https://habr.com/ru/post/982313/


All Articles