grails单元测试+线程 [英] grails unit test + Thread
问题描述
我有grails函数,在这里我使用单独的线程:
I having a grails function, where I am using a separate Thread:
def testFunction() {
//.....
Thread.start() {
testService.somefunction()
}
//...
}
在单元测试中,我正在像这样模拟服务功能:
In the unit test, I'm mocking the service function like this:
def "test testfunction" {
//...
1 * testService.somefunction(_)
//..
}
但是,由于Spock未能检测到该方法是在单独的线程上执行的,因此出现了无法匹配的调用错误.
However, I get the unmatched invocations error, because Spock didn't detect that the method was executed on the separate thread.
1 * testService.somefunction(_) (0 invocations)
Unmatched invocations (ordered by similarity):
我尝试使用此 http://spock-framework.阅读了thethedocs.org/en/latest/new_and_noteworthy.html#polling-conditions ,但没有成功.
I tried using this http://spock-framework.readthedocs.org/en/latest/new_and_noteworthy.html#polling-conditions, but didn't have any success.
已更新以包含代码示例:
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"
}
}
推荐答案
不幸的是,对于您的原始代码,您无法以传统方式测试调用次数,因为在闭包中必须声明条件,因为闭包不是在spock执行器的上下文中.我会推荐这样的东西,它对我有用:
Per your original code, you unfortunately cannot test number of invocations in the traditional way because within a closure you have to you assert the condition because the closure isn't in the context of the spock executor. I would recommend something like this, which has worked for me:
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
}
}
给出服务"中的方法:
public void aMethod(){
Thread.start{
sleep(5000)
println "awake!"
someService.methodExecutedInThread("some param")
}
}
根据您更新的代码示例:
Based on your updated code example:
不幸的是,您正在尝试测试响应,但是不幸的是,如果您是从线程内发送响应,则此操作将无效.不知道实际功能是什么样子,我不能说更多.但是,我上面提到的内容应该可以回答您的原始问题.
Unfortunately, you are trying to test a response and this unfortunately won't work if you are sending the response from within a thread. Without seeing what the actual function looks like, I can't say more. However, what I've placed above should help answer your original question.
这篇关于grails单元测试+线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!