我列出了一些对象 - 让我们假设公司。现在,我想检查此列表是否包含具有某些名称但未考虑订单的公司。目前我正在使用这样的结构:
companyList.name.sort() == ["First", "Second"]
Spock或Groovy中是否有任何运算符允许我比较没有顺序的数组?
答案 0 :(得分:14)
据我所知,没有这样的操作员。如果列表不包含任何重复项,则可以使用以下断言:
companyList.name as Set == ["First", "Second"] as Set
或类似的东西:
companyList.name.size() == ["First", "Second"].size() && companyList.name.containsAll(["First", "Second"])
答案 1 :(得分:11)
您可以在Spock中使用Hamcrest支持,并使用为此案例明确设计的Matcher
- containsInAnyOrder
。您需要以下导入:
import static org.hamcrest.Matchers.containsInAnyOrder
import static spock.util.matcher.HamcrestSupport.that
然后您可以按如下方式编写测试代码:
given:
def companyList = [ "Second", "First"]
expect:
that companyList, containsInAnyOrder("First", "Second")
这比使用.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"
如果您使用then:
代替expect:
,则可以使用expect
代替that
导入以提高可读性。
then:
expect companyList, containsInAnyOrder("First", "Second")
答案 2 :(得分:1)
为@Opal回答,它可能是最好的。作为好奇心,我只会添加减号运算符的使用示例来比较两个未排序的列表:
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 [[]]
}
}
如果其中一个列表包含冗余数据,它也可以工作。