首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何防止服务的metaClass被重写

如何防止服务的metaClass被重写
EN

Stack Overflow用户
提问于 2014-12-23 23:55:10
回答 1查看 92关注 0票数 0

我试图在集成测试中模拟对外部服务的调用,该服务在grails webflow中使用。该服务不在流或会话作用域中,而是通过依赖注入添加的,请参阅here

我已经设法想出了一种方法,通过使用ExpandoMetaClass替换服务的metaClass来覆盖服务。这些更改仅在测试单独运行时生效,如果在此测试之前运行了使用相同服务的另一个测试,则metaClass更改将消失。

覆盖metaClass的部分:

代码语言:javascript
复制
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
}

相关问题:How to change a class's metaClass per test

有没有办法将我的更改保存到测试中,或者是否有其他方法覆盖该服务。

EN

回答 1

Stack Overflow用户

发布于 2014-12-24 13:04:38

如果您想要在每个测试方法的测试用例中覆盖服务,有一种更简单的方法。看一个例子:

代码语言:javascript
复制
class SomeControllerSpec extends Specification {

    def someService

    void "test any external method for success response"() {
        given: "Mocked service method"
        someService.metaClass.accessAnotherSystem = { arg1, arg2 ->
            return "some success response"
        }

        when: "Any controller method is called which calls this service method"
        // Your action which calls that service method

        then: "Result will processed coming from mocked method"
        // Your code
    }
}

您可以对任何服务测试方法执行相同的操作。如果您想模拟您正在为其编写测试用例的同一服务的方法,那么请执行以下操作。

代码语言:javascript
复制
class SomeServiceSpec extends Specification {

    def someService

    void "test external method call"() {
        given: "Mocked service method"
        someService.metaClass.methodA = { arg1, arg2 ->
            return "some success response"
        }

        when: "A method is called which invokes the another method"
        // Your another service method which call the same method
        someService.methodB()    // Where methodB() invokes the methodA() internally in your code

        then: "Result will processed coming from mocked method"
        // Your code
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27623737

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档