如何重置Groovy中的模拟静态方法? [英] How do I reset a mocked static method in Groovy?
问题描述
在测试设置中我有以下几项:
def originalPostAsXml = RestClient。& postAsXml
RestClient.metaClass.'static'.postAsXml = {
String uriPath,String xml - >
return 65536
}
并在测试清理中:
RestClient.metaClass.'static'.postAsXml = originalPostAsXml
但是,当下一次测试运行时,当它尝试执行RestClient.postAsXml时,它会运行到StackOverflowError:
at groovy.lang.Closure.call(Closure.java:282)
它看起来像RestClient.postAsXml递归地指向自己。什么是重置模拟静态方法的正确方法?
在单元测试中,我经常将元类设置为在
,这似乎允许类在没有修改的情况下像原来一样工作。 > tearDown()
中使用code> null
例子:
void setUp(){
super.setUp ()
ServerInstanceSettings.metaClass.'static'.list = {
def settings = [someSetting:'myOverride'] as ServerInstanceSettings
return [settings]
}
}
void tearDown(){
super.tearDown()
ServerInstanceSettings.metaClass.'static'.list = null
}
如果您使用的是JUnit4,则可以使用 @AfterClass
也许更有意义。
I have the following in the test setup:
def originalPostAsXml = RestClient.&postAsXml
RestClient.metaClass.'static'.postAsXml = {
String uriPath, String xml ->
return 65536
}
and in the test cleanup:
RestClient.metaClass.'static'.postAsXml = originalPostAsXml
But when the next test runs, when it tries to execute RestClient.postAsXml, it runs into a StackOverflowError:
at groovy.lang.Closure.call(Closure.java:282)
It looks like RestClient.postAsXml recursively points to itself. What's the right way to reset a mocked-out static method?
In a unit test, I often set the metaclass to null
in the tearDown()
which seems to allow the class to work as it did originally without my modifications.
example:
void setUp() {
super.setUp()
ServerInstanceSettings.metaClass.'static'.list = {
def settings = [someSetting:'myOverride'] as ServerInstanceSettings
return [settings]
}
}
void tearDown() {
super.tearDown()
ServerInstanceSettings.metaClass.'static'.list = null
}
If you are using JUnit4 you can use @AfterClass
instead in this case which makes more sense perhaps.
这篇关于如何重置Groovy中的模拟静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!