Mockito - thenReturn always returns null object

Instead of creating a equals method in your BPRequestVO class you can create a mock argument with "any(YourObject.class)" like this:

when(mockBPService.getProduct(any(BPRequestVO.class))).thenReturn(invalidServiceResponse);

The instance of BPRequestVO that you use with when() is different than the one used in getTestData().
Unless you override equals(), they will not match.

You should not need to write a custom Matcher if you override equals(). Note the following from the Mockito documentation:

"Custom argument matchers can make the test less readable. Sometimes it's better to implement equals() for arguments that are passed to mocks (Mockito naturally uses equals() for argument matching). This can make the test cleaner."


The problem is in your usage of when().

You submit a reference to a constructed instance; as a result, the mocking will return what you want only if the argument passed to the method is the same reference.

What you want is an argument matcher; something like:

when(mockBPService.getProduct(argThatMatches(someBPRequestVO))
    .thenReturn(whatYouWant);

Of course, it requires that you write the argument matcher!

Note that there is a builtin matcher which can do what you want:

when(mockBPService.getProduct(eq(someBPRequestVO))).thenReturn(whatYouWant);

This matcher of course requires that your BPRequestVO class implements equals() (and hashCode() too)!

Tags:

Java

Null

Mockito