如何重置Groovy中的模拟静态方法?

编程入门 行业动态 更新时间:2024-10-25 10:27:31
本文介绍了如何重置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中的模拟静态方法?

本文发布于:2023-10-31 04:04:41,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   方法   Groovy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!