I am new to Mockito and trying to handle a scenario.
I have a class that i am spying on;
//Production Code Starts
class LoginRequest {
final Callable<String> buildRequest() {
callABC();
callXYZ();
Callable<String> callableObject = createCallable();
return callableObject;
}
final Callable<String> buildRequest(CallBack callBackObject) {
callABC();
callXYZ();
Callable<String> callableObject = createCallable(callBackObject);
return callableObject;
}
}
LoginRequest createLoginRequest() {
LoginRequest loginRequest = new LoginRequest();
return loginRequest;
}
Callable<String> callable = loginRequest.buildRequest();
Netowrk.submit(callable);
//Production Code ends
Now, What I want is, that when call to
loginRequest.buildRequest()
is made it should instead be propagated to the parameter version of the method;
so instead of calling
buildRequest()
it should call
buildRequest(callBackObject);
So I have tried the following;
//Test Code Starts
LoginRequest createLoginRequest() {
final LoginRequest loginRequest = new LoginRequest();
final LoginRequest spy = Mockito.spy(loginRequest);
final CallBack callBackObject = new CallBack()//my CallBack object
Mockito.when(spy.buildRequest()).thenAnswer(new Answer<Callable<?>>() {
@Override
public Callable<String> answer(InvocationOnMock invocation)
throws Throwable {
Callable<String> callable = spy.buildRequest(callBackObject);
return callable;
}
});
return spy;
}
I was expecting that when
loginReuest.buildRequest()
be called from production code it would propagated to
Answer.answer() {}
and then to
buildRequest(callBackObject);
from there.
However what is happening is, that when call to original
loginReuest.buildRequest()
method from the production code is made, it actually calls the original
buildRequst()
and from there call to
callABC()
is made, which in turn calls my anonymous
Answer.answer();
and end up calling
callable = spy.buildRequest(callBackObject);
and enters in recursive calls and then stack overflow.
Is there a better way better to do this kind of thing.
I appreciate your help
Thanks
Big O