简体   繁体   中英

Is it possible to override a call to an injector?

I'm new to Spock and Guice. I'm trying to test my class, but I don't know how to override the below call with an interaction.

Testing:

 @Shared def INSVariableResolver resolver  // just a wrapper of my injector, it's an interface                         
 @Shared def MyInterface myMock = Mock()

 def setupSpec(){
     given:
          injector = Guice.createInjector(modules)
          resolver = injector.getInstance(INSVariableResolver)
          resolver.getInstance(MyInterface.class) >> myMock  // INTERACTION
 }

 def "some test"(){
     given:
          AnotherInterface someObject = resolver.getInstance(AnotherInterface)
     expect:
          someObject.doSomething() == someValue
 }

The implementation of AnotherInterface:

class AnotherClass implements AnotherInterface{
     @Inject
     INSVariableResolver resolver;
     public int doSomething(){
         .
         .
         MyInterface i = resolver.getInstance(MyInterface.class);  // (*) trying to override this call
         .
         .
     }    

But it doesn't work; i is the real object at line marked with (*), it's not a mock. I don't want to change neither the implementation nor the AbstractModule(s).

Is it possible to do what I want to do? Am I using the interaction in a wrong way? Thanks

UPDATE: I only need a mock of MyInterface inside AnotherClass.

You shouldn't mock Guice with Spock, but can configure Guice to inject a mock instead of the real instance, by overriding a module.

def setupSpec(){
   injector = Guice.createInjector(Modules.override(modules).with(new Module() {
      public void configure(Binder binder) {
        binder.bind(MyInterface).toInstance(myMock)
      }
   });
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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