Writing Junit unit testcase, I am trying to mock method callservice using Mockito.
public CompletableFuture<String> getInfo(String something)
{
CompletableFuture<String> future = new CompletableFuture<>();
JAXBElement<Class1> request = SoapRequests
.buildRequest(str1, str2);
Consumer<Exception> exception = ex->{
future.complete("exception");
}
Consumer<FaultType> fault = fault->{
future.complete("exception",FaultType.class);
}
String target="target";
JAXBElement<?> element = soapConnector.callservice(
target, request,
fault, ex, false);
}
I have tried the following way. But, it is always return with null element
JAXBElement<?> response = jaxbUnmarshaller.unmarshal("xmlString",
SomeClass12.class);
JAXBElement<SomeClass> request = SoapRequests
.buildRequest("", "", "");
JAXBElement<SomeClass> requestSpy = spy(request);
Consumer<FaultType> faultType = mock(Consumer.class);
Consumer<Exception> exception = mock(Consumer.class);
lenient().when(soapConnector.callservice(
"target", requestSpy,
faultType, exception, false)).thenAnswer(i->response);
If you want to mock a method with parameters mockito uses the equal method to compare the parameters. If they equal the parameters the mock is called with, the mock returns the value. If there is no match found, your mock will return null. In your case the equality check will never return true since some of the parameters are local to your testcase, and thus the mock returns null.
Examples to explain this better:
Assume following class:
in our test we do:
As we can see only if the argument matches our mock returns the specified value.
Comming back to your case, specifically requestSpy is not equal to request in the actual code, neither are both the consumer mocks since they are local variables and also are mocks.
I am not quite sure what you are trying to do but it's not necessary to pass mocks while mocking a function. A possible way to correctly mock you function would be:
This way we ensure the parameters target and false are provided and don't really care for the other parameters. If you want to check on the parameters use an ArgumentCaptor.
Also notice how I explicitly defined the Generic-Parameter to the when()-function to ensure the typing ist correct.
Used static imports: