【问题标题】:How to keep service's metaClass from being overridden如何防止服务的元类被覆盖
【发布时间】:2014-12-24 13:04:38
【问题描述】:

我正在尝试在集成测试中模拟对外部服务的调用,该服务用于 grails webflow。该服务不在流或对话范围内,但通过依赖注入添加,请参阅here

我已经设法找到一种方法来覆盖服务,方法是使用 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
}

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

有没有办法保留我对测试所做的更改,或者有其他方法可以覆盖服务。

【问题讨论】:

  • 您在应用中的何处添加了此代码?
  • 在测试类之前的任何测试方法。

标签: grails dependency-injection integration-testing spring-webflow expandometaclass


【解决方案1】:

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

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
    }
}

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

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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-03
    • 2017-12-19
    • 2021-02-08
    • 2020-07-23
    • 2018-11-18
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多