我试图在集成测试中模拟对外部服务的调用,该服务用于 grails webflow。该服务不在流或对话范围内,而是通过依赖注入添加,请参见此处。
我已经设法找到一种方法来通过使用 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('test_method_I_Want_failure_in')
{
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
}
相关问题:如何更改每个测试的类的元类
有没有办法保留我对测试的更改,或者有其他方法可以覆盖服务。