在纯 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
}
这使得测试非常可读。
关于groovy - 如何在 Spock 中断言列表仅包含某个特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55919673/