Reputation: 351
I need to unit test reduce()
method. Not sure why it is throwing NullPointerException
, though I can see the object is not null.
Please refer the below code.
Mock:-
when(mergeUtility.mergeJson(josnObj1, jsonObj2)).thenReturn( new
JsonParser().parse(MergeConstant.mergedJsonObject).getAsJsonObject());
Actual method:
Optional<JsonObject> aggregatedJson =
jsonList.stream().reduce(mergeUtility :: mergeJson);
When I am testing jsonList
has to objects, still NullPointerException
is getting thrown from reduce()
method. Could someone please let me know the reason?
Upvotes: 0
Views: 443
Reputation: 371
Try the code below :-
when(mergeUtility.mergeJson(Mockito.any(), Mockito.any())).thenReturn( new
JsonParser().parse(MergeConstant.mergedJsonObject).getAsJsonObject());
The reason behind it is though you are mocking the method but you are sending the
parameters as josnObj1, jsonObj2
which are different than the objects generated by jsonList while executing your test case, so when you do an equals operation on the items generated by the list and the josnObj1, jsonObj2
they won't match.As the objects are not matching the method call does not match to the one you have mocked hence mocking is not performed.
Whereas when you use Mockito.any()
it will mock the method irrespective of the parameter which is given to the method even though they don't match.
Upvotes: 3