我有一些对象列表 - 让我们假设公司.现在,我想检查此列表是否包含具有某些名称但未考虑订单的公司.目前我正在使用这样的结构:
companyList.name.sort() == ["First", "Second"]
Spock或Groovy中是否有任何运算符允许我比较没有顺序的数组?
Opa*_*pal 15
据我所知,没有这样的操作员.如果列表不包含任何重复项,则可以使用以下断言:
companyList.name as Set == ["First", "Second"] as Set
Run Code Online (Sandbox Code Playgroud)
或类似的东西:
companyList.name.size() == ["First", "Second"].size() && companyList.name.containsAll(["First", "Second"])
Run Code Online (Sandbox Code Playgroud)
tdd*_*key 13
您可以在Spock中使用Hamcrest支持并在Matcher本案例中明确使用设计 - containsInAnyOrder.您需要以下导入:
import static org.hamcrest.Matchers.containsInAnyOrder
import static spock.util.matcher.HamcrestSupport.that
Run Code Online (Sandbox Code Playgroud)
然后您可以编写测试代码,如下所示:
given:
def companyList = [ "Second", "First"]
expect:
that companyList, containsInAnyOrder("First", "Second")
Run Code Online (Sandbox Code Playgroud)
这有利于使用.sort(),因为列表中的重复元素将被正确考虑.以下测试将使用Hamcrest失败但通过使用.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"
Run Code Online (Sandbox Code Playgroud)
如果您使用then:而不是expect:您可以使用expect而不是that导入可读性.
then:
expect companyList, containsInAnyOrder("First", "Second")
Run Code Online (Sandbox Code Playgroud)