unit-testing - Spock交互中如何匹配集合内容?

标签 unit-testing spock

假设我在模拟的类中有以下方法:

class Foo {
   public void doSomething(Collection<String> input) {
     //...
   }
}

现在我在 Spock 测试中模拟这个类,我想验证交互:

def test() {
    setup:
    def myMock = Mock(Foo)

    when:
    def hashSet = new HashSet<String>(['foo', 'bar'])
    myMock.doSomething(hashSet)

    then:
    1 * myMock.doSomething(['foo', 'bar'])

}

但是此交互不会触发。真正奇怪的是输出告诉我:

too few invocations for:

1 * myMock.doSomething(['foo', 'bar'])   (0 invocations)

Unmatched invocations (ordered by similarity):

1 * myMock.doSomething(['foo', 'bar'])

所以它基本上告诉我,没有任何调用看起来像我期待的那样,但还有另一个......呃看起来像我期待的那个。

我在这里做错了什么,还是这是 Spock 的限制,我需要检查闭包中的集合内容

1 * mock.doSomething( { it == ['foo', 'bar'] })

最佳答案

这都是因为 HashSet 的实例作为参数传递给模拟调用,而 List 的实例在 when block 中传递。 [] 是 groovy 中的 ArrayList - 存在类型不匹配 - 但 SetList 都打印到控制台非常相似。以下测试运行良好:

@Grab('org.spockframework:spock-core:0.7-groovy-2.0')
@Grab('cglib:cglib-nodep:3.1')

import spock.lang.*

class Test extends Specification {

    def "test"() {
        setup:
        def lol = Mock(Lol)

        when:
        def hashSet = new HashSet<String>(['foo', 'bar'])
        lol.doSomething(hashSet)

        then:
        1 * lol.doSomething(new HashSet<String>(['foo', 'bar']))
    }
}

class Lol {
   public void doSomething(Collection<String> input) {
       println input
   }
}

关于unit-testing - Spock交互中如何匹配集合内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29408702/

相关文章:

node.js - Mocha 单元测试 Mongoose 模型

java - 读取包含输入值的文件并使用结果生成 .out

spock - 在 stub 返回值时使用闭包验证调用参数

unit-testing - 如何使用 Spock 模拟有效地模拟流畅的界面?

groovy - Spock - 未收到测试事件, "NO-SOURCE"

ios - 核心数据单元测试 - 不确定如何在 executeFetchRequest :error: 中触发错误案例

java - 使用 Guice 进行模拟并拥有用于测试目的的真实对象

java - 模拟构建类 AWS Logs 客户端构建器

spring-mvc - 在 Spring Boot Spock 规范中使用 RestTemplate 并定制 Jackson

java - 无法在 Spring 中配置用于集成测试的模块 - 没有可用的任务