当前位置: 首页 > 知识库问答 >
问题:

如何使用mocks用groovy-spock编写参数化测试

施令秋
2023-03-14

我想用groovy和Spock测试这个类:

class TaskRunner {
    private int threads
    private ExecutorService executorService
    private TaskFactory taskFactory

    // relevant constructor

    void update(Iterable<SomeData> dataToUpdate) {
        Iterable<List<SomeData>> partitions = partition(dataToUpdate, THREADS)
        partitions.each {
            executorService.execute(taskFactory.createTask(it))
        }
    }
}
class TaskRunnerSpec extends specification {
    ExecutorService executorService = Mock(ExecutorService)
    TaskFactory taskFactory = Mock(TaskFactory)
    @Subject TaskRunner taskRunner = new TaskRunner(taskFactory, executorService)

    def "should run tasks partitioned by ${threads} value"(int threads) {
        given:
        taskRunner.threads = threads

        where:
        threads | _
              1 | _
              3 | _
              5 | _

        when:
        tasksRunner.update(someDataToUpdate())

        then:
        // how to test number of invocations on mocks?
    }
}

共有1个答案

公冶鸣
2023-03-14

简短回答是的,它们可以组合,但不能按这种顺序组合参见docs,其中必须是最后一个块。因此givised-when-then-where非常好。正确地测试多线程代码要困难得多,但是由于模拟了ExecutorService,所以不必担心它。

不要忘记@unroll并注意模板没有使用GString语法。

class TaskRunnerSpec extends specification {
    ExecutorService executorService = Mock(ExecutorService)
    TaskFactory taskFactory = Mock(TaskFactory)
    @Subject TaskRunner taskRunner = new TaskRunner(taskFactory, executorService)

    @Unroll
    def "should run tasks partitioned by #threads value"(int threads) {
        given:
        taskRunner.threads = threads

        when:
        tasksRunner.update(someDataToUpdate())

        then:
        threads * taskFactory.createTask(_) >> new Task() // or whatever it creates
        threads * executorService.execute(_)

        where:
        threads | _
              1 | _
              3 | _
              5 | _

    }
}
 类似资料:
  • 我希望在Spock中使用@WithMockUser运行一个参数化测试,每个迭代都有不同的角色。 作为一个示例,下面的测试代码没有显示编译错误,并且运行两次。但是结果失败了,因为#role只在@unroll中解析,而不在@WithMockUser注释中解析。 所以我的问题是:有可能运行这样一个参数化的测试吗?

  • 问题内容: 我正在GoLang中为一个简单的REST服务编写测试。但是,因为我使用julienschmidt / httprouter 作为路由库。我正在努力编写测试。 main.go 控制器 我的问题是:当GetBook既不是HttpHandler也不是HttpHandle时如何测试呢? 如果我使用传统的处理程序,这样的测试将很容易 问题是,httprouter不是处理程序,也不是handlef

  • 注意:我已经做了一个搜索和阅读了各种博客,但找不到一个例子,与我正在尝试做什么。 它似乎不喜欢我的某个测试成员字段是私有的,但没有告诉我它对哪个字段有问题。我见过的单元测试的所有例子,唯一公开的一定是ExpectedException规则。

  • 问题是我对程序的输入是整数数据类型,输出是双数据类型。因此,在编写参数化JUnit测试用例时,assertEquals会自动删除。。。显示2个错误。它们如下:-类型Assert中的方法assertEquals(double,double)已被弃用-类型循环中的方法findarea(int)不适用于参数(int,double) 这里方法findarea是我查找循环区域的方法。这是我的密码。 这是我的

  • 我有一个由Gradle2.4构建的Java库,它将被一些Java6应用程序、一些Java7应用程序、一些Java8应用程序和一些Groovy2.x应用程序使用。因此,为了尽可能地向后兼容,我编写的lib具有和1.6: 但是,我没有理由不能用Groovy/Spock编写单元测试。只要Groovy不是main/compile/runtime类路径的一部分,那么我就可以自由地用任何JVM语言编写测试!我