简体   繁体   English

如何模拟Autowired对象(java)并将其内部注入Spock中的间谍对象

[英]How to mock Autowired objects(java) and inject inside to a spy object in Spock

How I can inject mock objects into a spied instance in Spock? 我如何将模拟对象注入Spock的间谍实例?

Example: 例:

TestClass 识别TestClass

class Service {

     @AutoWired
     private Util util;

     public void testMethod(int a, int b) {

         int c = sum(a,b);
         util.format(c);
     }

     private int sum(int a, int b) {
        ......
     }
}

Spock: 斯波克:

def "testMethod with valid inputs"() {

    given:
       def serviceSpy    = Spy(Service)
       //spy.util          = Mock(Util) I can't do this
       spy.sum(_,_) >> 2

    ......
}

So, My doubt is how I can inject a mock object into the spied instance? 那么,我怀疑的是我如何将模拟对象注入到间谍实例中?

I tried to spy the existing instance, but it's not stubbing the method that's in the test class. 我试图窥探现有的实例,但它不是在测试类中的方法。

Could someone suggest me, what I can do here? 有人可以建议我,我能在这做什么? Or Can I solve it easily using Junit(Mockito)? 或者我可以使用Junit(Mockito)轻松解决吗?

You can use "constructorArgs" 你可以使用“constructorArgs”

Here is an example: 这是一个例子:

def util = Stub(Util) // or whatever
def serviceSpy = Spy(Service, constructorArgs: [util])

To make it work, however, don't use @Autowire on fields. 但是,要使其工作,请不要在字段上使用@Autowire Leaving aside the fact that spring runs it in real life, for a test like this you probably do not have spring. 暂且不谈弹簧在现实生活中运行的事实,对于这样的测试,你可能没有弹簧。 So putting the dependency reference explicitly will break encapsulation and doesn't work in any case. 因此,明确地放置依赖引用将破坏封装,并且在任何情况下都不起作用。

Instead, I suggest using Constructor dependency: 相反,我建议使用Constructor依赖:

class Service {

    private final Util util;

    @Autowired // in recent versions of spring no need to use this annotation
    public Service(Util util) {  
      this.util = util;
    }
}

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

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