Search code examples
unit-testinggrailsgroovyspock

Groovy Spock BlockingVariable never released


I am fighting a loosing battle against Spock unit tests in my Grails application. I want to test async behavior and in order to get familiar with Spock's BlockingVariable I've written this simple sample test.

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()
}

Unfortunately it is not a good thing, because otherwise it would come to an end. When I set a breakpoint at Thread.sleep() and debug the test, that breakpoint is never hit. What am I missing?


Solution

  • Your test is broken, because you don't actually run the thread you create. Instead:

    when:
    new Thread(runner)
    

    you should do:

    when:
    new Thread(runner).run()
    

    and then your test succeeds after approximately 5 seconds.