Search code examples
javajunitmockitopowermockito

How to mock local object creations in JUnit


I am not aware about how to mock local objects within a method using JUnit and mockito.

JDK - 1.7, JUnit - 4.12, powermock-module-junit4 - 1.6.6, powermock-api-mockito - 1.6.6

Also, bringing in the point that I must use only JDK 1.7.

In the below sample class, how do mock "service" object which is at method scope.

class A {
public String methodA() {

SampleService service = new SampleService();
return service.retrieveValue();

}
}

Please suggest.


Solution

  • You can't mock local variable. But you can do following:

    1) Create a Factory and inject int o tested class. After that refactoring you could mock the factory and provide mocked service to tested object.

    class A {
        private SampleServiceFactory factory;
        public String methodA() {
            SampleService service = factory.createSampleService();
            return service.retrieveValue();
        }
    }
    

    In test you should inject factory mock and after that return mock of the service on createSampleService() call:

    when(mockFactory.retrieveValue()).thenReturn(mockService);
    

    2) You can extract method and override it in the test and return mock instead of the implementation:

    class A {
        public String methodA() {
            SampleService service = createSampleService();
            return service.retrieveValue();
        }
    
       protected SampleService createSampleService() {
         return new SampleService();
       }
    }
    

    In this approach you can do following: @Test

    public void testServiceCall() {
       A testedObject = new A() {
           @Override
           protected SampleService createSampleService() {
             return mockSampleService;
           }
       }
       ...
       testedObject.methodA();
       ...
       verify(service).retrieveValue();
    }
    

    PS: I would prefer first one, access modifier changing is not the best approach by my opinion.