grails单元测试+线程

时间:2014-10-13 17:30:11

标签: grails spock

我有一个grails函数,我在使用一个单独的Thread:

def testFunction() {
   //.....
   Thread.start() {
     testService.somefunction()
   }
   //...

}

在单元测试中,我嘲笑服务功能如下:

def "test testfunction" {
   //...
   1 * testService.somefunction(_)
   //..
}

但是,我得到了无法匹配的调用错误,因为Spock没有检测到该方法是在单独的线程上执行的。

1 * testService.somefunction(_)   (0 invocations)
Unmatched invocations (ordered by similarity):

我尝试使用此http://spock-framework.readthedocs.org/en/latest/new_and_noteworthy.html#polling-conditions,但没有取得任何成功。

已更新以包含代码示例:

void "test without errors"() {

        def conditions = new PollingConditions(timeout: 15)

        def cmdList = new ArrayList<CommandClass>()
        parseService.parseFile(file, _) >> commandList
        nextService.create(_) >>  commandList
        controller.controllerService = nextService
        controller.controllerParseService = parseService

        when:
        controller.testFunction()

        then:
        conditions.eventually {
            assert response.contentAsString == "SUCCESS"
        }
    }

1 个答案:

答案 0 :(得分:4)

根据您的原始代码,遗憾的是您无法以传统方式测试调用次数,因为在闭包内您必须断言条件,因为闭包不在spock执行器的上下文中。我会推荐这样的东西,这对我有用:

def "test concurrency"(){
        given:
            def conditions = new PollingConditions(timeout: 15)
            MyService service = new MyService()
            SomeService someService = Mock()
            service.validationService = someService
            int numInvocations = 0
            someService.methodExecutedInThread(_) >> {
                numInvocations++
                return null
            }
        when:
            int i = 0
            service.aMethod()
        then:
            conditions.eventually {
                println "checked ${i}" // <--- you should see this checking repeatedly until the condition is met 
                i++
                assert numInvocations == 1
            }
    }

给出&#34; service&#34;中的方法:

  public void aMethod(){
        Thread.start{
            sleep(5000)
            println "awake!"
            someService.methodExecutedInThread("some param")
        }
    }

根据您更新的代码示例:

不幸的是,您正在尝试测试一个响应,如果您从一个线程中发送响应,这很遗憾。没有看到实际功能的样子,我就不能多说了。但是,我上面提到的内容应该有助于回答您原来的问题。