gpt4 book ai didi

grails - 如何在每个测试中更改类的metaClass

转载 作者:行者123 更新时间:2023-12-02 16:03:52 25 4
gpt4 key购买 nike

我正在使用ExpandoMetaClass来使服务始终在集成测试中返回成功,但是我希望有一个实际上失败的测试。

ExpandoMetaClass的使用示例:

static {
ExpandoMetaClass someService = new ExpandoMetaClass(Object, false)
someService.accessAnotherSystem = { return 'success' }
someService.initialize()
SomeService.metaClass = someService
}

注意:目前尚未为 Controller 定义服务,但由于它是一个Spring bean,因此引用了 SomeService之类的类 someService.accessAnotherSystem()可以正常工作,即 Controller 中没有 def someService

因此,我无法从集成测试中执行 controller.someService.metaClass.accessAnotherSystem = { return 'failure'}

另请注意:这是针对Webflow的集成测试。

是否可以为一个测试重置metaClass,或者以某种方式重置我想要的东西?

最佳答案

如果单独运行测试,则下面的方法工作正常,但是如果之前运行了另一个使用SomeService的测试,则ExpandoMetaClass将被覆盖。我将针对这个问题提出另一个问题。

static {
ExpandoMetaClass someService = new ExpandoMetaClass(Object, false)
someService.invokeMethod = { String name, args ->
def result = 'success'
if(name.equals('accessAnotherSystem')
{
StackTraceUtils.sanitize(new Throwable()).stackTrace.each
{
if(it.methodName.equals('method_I_Want_failure')
{
result = 'exception'
}
}
return result
}

def validMethod = SomeService.metaClass.getMetaMethod(name, args)
if (validMethod != null)
{
validMethod.invoke(delegate, args)
}
else
{
SomeService.metaClass.invokeMissingMethod(delegate, name, args)
}
}
someService.initialize()
SomeService.metaClass = someService
}

关于grails - 如何在每个测试中更改类的metaClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27533910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com