I have to unit test a method of a groovy class which uses sleep() to delay processing i开发者_如何转开发n a loop.
Obviously I don't want my test suite to sleep really, so I tried to mock the sleep() call in my class:
MyClass.metaClass.sleep = { return }
I tried a few variations of this with no success.
Can someone tell me the correct way to mock this language method?
You could wrap all calls to system functions with an interface. This way you can mock calls to any method you would like. This does increase code complexity though, so you will have to decide if it is worth it.
You need to be explicit in the arguments, and match the method you're overriding explicitly. Relying on the default "it" parameter doesn't work. Notice that overriding the static method only works when we state that the parameter is a "long" (and it's a static method, not an instance method):
def s = ""
def firstCalled = false
def secondCalled = true
s.metaClass.static.sleep = { firstCalled = true }
assert firstCalled == false
s.metaClass.static.sleep = { long ms -> firstCalled = true }
assert secondCalled == true
The code probably calls Thread.sleep
doesn't it?
You can do this:
Thread.metaClass.static.sleep = { long time -> println "Sleep for $time" }
But I'm not sure it's what you want...
This works for me:
class Foo {
def longSleep() { sleep 10000000 }
}
Foo.metaClass.sleep = { int ms -> println "no sleep" }
new Foo().longSleep()
Update from tim_yates: sleep(ms) is added to Object in the Groovy JDK. More info here: http://groovy.codehaus.org/groovy-jdk/java/lang/Object.html
精彩评论