简体   繁体   English

Grails单元测试服务MissingProperty'log'

[英]Grails Unit Test Service MissingProperty 'log'

I want to run a unit test for a service. 我想为服务运行单元测试。 The method I want to test includes a some log.debug() statements. 我要测试的方法包括一些log.debug()语句。 While the log property is injected at runtime, it does not seem to be injected in tests, so it throws groovy.lang.MissingPropertyException: No such property: log for class: 虽然log属性是在运行时注入的,但它似乎并未在测试中注入,因此它抛出groovy.lang.MissingPropertyException: No such property: log for class:

This is my unit test class: 这是我的单元测试课:

@TestFor(ServiceUnderTest)
@Mock([ServiceUnderTest])
class ServiceUnderTestTests {

    def test() {
        def mock = [ mockedProp: [...] ] as ServiceUnderTest
        def info = mock.doOperation()
        assert ....
    }
}

I've also tried adding MockUtils.mockLogging(ServiceUnderTest) but with no success. 我也尝试添加MockUtils.mockLogging(ServiceUnderTest)但没有成功。

How can I get the log property properly injected in my service class while in unit tests? 在单元测试中,如何获取正确注入到服务类中的log属性?

You do not have to have the test class annotated with @Mock([ServiceUnderTest]) . 您不必使用@Mock([ServiceUnderTest])注释测试类。 @TestFor(ServiceUnderTest) detects its a service class and does all the mocking automatically. @TestFor(ServiceUnderTest)检测到它的服务类并自动进行所有@TestFor(ServiceUnderTest) It also adds a service property to the test class that can be accessed in all the test methods and mocks the log property accordingly. 它还向测试类添加了一个service属性,可以在所有测试方法中访问该service属性,并相应地模拟log属性。

I think the problem why neither mocking nor explicit log mocking with MockUtils.mockLogging(ServiceUnderTest) does work in your case is the as coercion you are using in your test method code: 我想,为什么没有嘲讽,也没有明确的日志与嘲讽问题MockUtils.mockLogging(ServiceUnderTest)做工作你的情况是as强迫你使用你的测试方法的代码:

def mock = [ mockedProp: [...] ] as ServiceUnderTest

Groovy internally uses java.lang.reflect.Proxy to create a proxy descendant class from ServiceUnderTest . Groovy在内部使用java.lang.reflect.ProxyServiceUnderTest创建代理后代类。 The proxy class does not see changes done to the ServiceUnderTest meta class like the added log property. 代理类看不到对ServiceUnderTest元类所做的更改,例如添加的log属性。

I would solve this issue by using a per-object meta class . 我将通过使用每个对象的元类来解决此问题。 You can mock the property getter (or setter) by altering the metaClass of the service object. 您可以通过更改service对象的metaClass来模拟属性getter(或setter)。 Be aware that meta-class changes are rolled back by Grails in-between execution of test methods: 请注意,在测试方法执行之间,Grails会回滚元类更改:

service.metaClass.mockedProp = {-> ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM