Srinath
Srinath

Reputation: 13

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?

Example:

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)?

Upvotes: 0

Views: 1984

Answers (1)

Mark Bramnik
Mark Bramnik

Reputation: 42491

You can use "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. 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:

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

Upvotes: 1

Related Questions