在测试设置中我有以下几项:
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 = originalPostAsXmlBut 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中的模拟静态方法?
发布评论