如何重置Groovy中的模拟静态方法? [英] How do I reset a mocked static method in Groovy?

查看:249
本文介绍了如何重置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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆