Groovy Spock BlockingVariable 从未发布

Groovy Spock BlockingVariable never released

我正在与我的 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() 处设置断点并调试测试时,该断点永远不会命中。我错过了什么?

你的测试失败了,因为你实际上没有 运行 你创建的线程。相反:

when:
new Thread(runner)

你应该做的:

when:
new Thread(runner).run()

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