首页 > 解决方案 > Groovy Spock BlockingVariable 从未发布

问题描述

在我的 Grails 应用程序中,我正在与 Spock 单元测试进行一场失败的战斗。我想测试异步行为,为了熟悉 Spock,BlockingVariable我编写了这个简单的示例测试。

void "test a cool function of my app I will not tell you about"() {
    given:
    def waitCondition = new BlockingVariable(10000)
    def runner = new Runnable() {
        @Override
        void run() {
            Thread.sleep(5000)
            waitCondition.set(true)
        }
    }

    when:
    new Thread(runner)

    then:
    true == waitCondition.get()
}

不幸的是,这不是一件好事,否则它就会结束。当我设置断点Thread.sleep()并调试测试时,该断点永远不会被命中。我错过了什么?

标签: unit-testinggrailsgroovyspock

解决方案


您的测试被破坏了,因为您实际上并没有运行您创建的线程。反而:

when:
new Thread(runner)

你应该做:

when:
new Thread(runner).run()

然后您的测试在大约 5 秒后成功。


推荐阅读