如何在 Spock 中断言列表只包含某些特定元素?
How to assert in Spock that list contains only some particular element?
在纯 Spock/Groovy 中,我需要两个单独的断言来验证列表包含一些元素而没有其他元素:
def "list has single element"() {
given:
def list = ['x']
expect:
list.size() == 1
list.first() == 'x'
}
我可以通过使用 Guava 依赖使这个断言成为单行:
expect:
Iterables.getOnlyElement(list) == 'x'
有没有办法在纯 Groovy/Spock 的单行中做同样的事情?我不想在测试中过多地使用 Guava。
编辑
其实对于这样一个简单的例子,list == ['x']
就足够了。当必须对此单个元素执行多个断言时,我正在寻找更复杂的非 Guava 解决方案:
def "list has single element"() {
given:
def list = [5.0]
expect:
def bigDecimal = Iterables.getOnlyElement(list)
bigDecimal.scale() == 1
bigDecimal.precision() == 2
}
如果可以创建辅助方法,可以使用 with()
:
def "list has single element"() {
given:
def list = [5.0]
expect:
with onlyElementOf(list), {
it.scale() == 1
it.precision() == 2
}
}
其中 onlyElementOf()
是
static <T> T onlyElementOf(Iterable<T> iterable) {
Iterator iterator = iterable.iterator()
def first = iterator.next()
assert !iterator.hasNext(), "Iterable has more than 1 element"
return first
}
这使得测试非常可读。
在纯 Spock/Groovy 中,我需要两个单独的断言来验证列表包含一些元素而没有其他元素:
def "list has single element"() {
given:
def list = ['x']
expect:
list.size() == 1
list.first() == 'x'
}
我可以通过使用 Guava 依赖使这个断言成为单行:
expect:
Iterables.getOnlyElement(list) == 'x'
有没有办法在纯 Groovy/Spock 的单行中做同样的事情?我不想在测试中过多地使用 Guava。
编辑
其实对于这样一个简单的例子,list == ['x']
就足够了。当必须对此单个元素执行多个断言时,我正在寻找更复杂的非 Guava 解决方案:
def "list has single element"() {
given:
def list = [5.0]
expect:
def bigDecimal = Iterables.getOnlyElement(list)
bigDecimal.scale() == 1
bigDecimal.precision() == 2
}
如果可以创建辅助方法,可以使用 with()
:
def "list has single element"() {
given:
def list = [5.0]
expect:
with onlyElementOf(list), {
it.scale() == 1
it.precision() == 2
}
}
其中 onlyElementOf()
是
static <T> T onlyElementOf(Iterable<T> iterable) {
Iterator iterator = iterable.iterator()
def first = iterator.next()
assert !iterator.hasNext(), "Iterable has more than 1 element"
return first
}
这使得测试非常可读。