risingTide risingTide - 2 months ago 20x
Java Question

Mockito - thenReturn always returns null object

I'm trying to implement Mockito to test a particular method but the .thenReturn(...) seems to always be returning a null object instead of what I intended:


public class TestClassFacade {

// injected via Spring
private InterfaceBP bpService;

public void setBpService(InterfaceBP bpService) {

this.bpService = bpService;

public TestVO getTestData(String testString) throws Exception {

BPRequestVO bpRequestVO = new BPRequestVO();

bpRequestVO.setGroupNumber(testString) ;
bpRequestVO.setProductType("ALL") ;
bpRequestVO.setProfileType("Required - TEST") ;

IBPServiceResponse serviceResponse = bpService.getProduct(bpRequestVO); //PROBLEM

if (serviceResponse.getMessage().equalsIgnoreCase("BOB")) {

throw new Exception();

} else {

TestVO testVO = new TestVO();

return testVO;


Spring Configuration:

<bean id="testClass" class="com.foo.TestClassFacade">

<property name="bpService" ref="bpService" />


<bean id="bpService" class="class.cloud.BPService" />

Mockito Test Method:

public class BaseTest {

@Mock BPService mockBPService;
@InjectMocks TestClassFacade mockTestClassFacade;

private String testString = null;
private BPRequestVO someBPRequestVO = new BPRequestVO();
private IBPServiceResponse invalidServiceResponse = new BPServiceResponse();

@Test (expected = Exception.class)
public void getBPData_bobStatusCode_shouldThrowException() throws Exception {


someBPRequestVO.setProfileType("Required - TEST");

System.out.println("1: " + someBPRequestVO.getGroupNumber());
System.out.println("2: " + someBPRequestVO.getProductType());
System.out.println("3: " + someBPRequestVO.getProfileType());
System.out.println("4: " + someBPRequestVO.getEffectiveDate());




System output:

1: null
2: ALL
3: Required - TEST
4: null

What's happening here is that when I run the test the serviceResponse object is null on the line in the CUT marked with //PROBLEM above. My desire is to have that object be populated with my "invalidServiceResponse" object from my test method. Judging from the output of my System.out.println's it appears that my bpRequestVO matches my someBPRequestVO in content.

Could some one show me what I'm missing here?

Thanks for your time!


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."