Context
I have a delegate class which is a sort of "dispatcher", with one only public
generic entry point (processRequest
) and a set of private
methods to compose the answer:
public class MyDelegateImpl implements MyDelegate {
@Override
public MyResponse processRequest(MyInput request)
{
//logic to determine a dispatch through the private methods
switch (methodToUse)
{
case 1:
return method1();
case 2:
return method2();
etc.
}
}
private MyResponse method1() {...}
private MyResponse method2() {...}
etc.
}
I am testing all the behaviors of this class using the framework JUnit
. One of the private
methods of this class contains a call to a public
and not static
method of an utility class called SOAPPricingHandler
, which performs SOAP calls to an external service:
private MyResponse methodN()
{
//...stuff
SOAPPricingHandler myHandler = new SOAPPricingHandler();
Document soapResponse = myHandler.getSoapAnswer();
//...other stuff
return someResponse;
}
For information, this is the basic structure of SOAPPricingHandler
:
public class SOAPPricingHandler {
public SOAPPricingHandler()
{
//some constructions
}
public Document getSoapAnswer()
{
//soap call, some reworking and then
return mySoapAnswerAsDocument;
}
}
Also, consider that MyDelegateImpl
is called in delegation, meaning that there is a generic class MyProxySession
which will create a future task and delegate the execution of its processRequest
method to the implementation of MyDelegate
.
Question
In order to unit test this behavior, I need to mock this part of code inside the private MyResponse methodN()
and not actually perform a SOAP request to the external service:
SOAPPricingHandler myHandler = new SOAPPricingHandler();
Document soapResponse = myHandler.getSoapAnswer();
However, I don't really understand how (and if) I can do it. I have tried the following:
@Test
public void myUnitTest()
{
...
SOAPPricingHandler soapRequestEngine = new SOAPPricingHandler();
SOAPPricingHandler spySoapRequestEngine = Mockito.spy(soapRequestEngine);
Mockito.when(spySoapRequestEngine.getSoapAnswer()).thenReturn(xmlExpectedAnswer);
MyResponse response = session.processRequest(someInput); //<-- the SOAPPricingHandler method will be called in here.
}
... but of course it doesn't work, because I'm not using the spied session of SOAPPricingHandler
inside the processRequest
(which is creating a new instance).
The same happens if I use this:
Mockito.doReturn(xmlExpectedAnswer).when(spySoapRequestEngine).getSoapAnswer();
Can anyone lead me through the proper design of this unit test? If you see some wrong design in the private MyResponse methodN()
which could be designed differently in order to have a better testability, I'm open to proposals as well.
Thanks in advance.