Reputation: 1157
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.
Upvotes: 1
Views: 1342
Reputation: 3572
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.
Upvotes: 2
Reputation: 77196
You don't. You fix the method so that SampleService
is injected either as a method parameter or as part of A
's constructor.
Upvotes: 1