4
votes

I am using mockito as mocking framework. I have a scenerio here, my when(abc.method()).thenReturn(value) does not return value, instead it returns null.

Here is how my class and test looks like.

public class foo(){  
 public boolean method(String userName) throws Exception {
    ClassA request = new ClassA();
    request.setAbc(userName);       
    ClassB response = new ClassB();
    try {
        response = stub.callingmethod(request);
    } catch (Exception e) {
    }

    boolean returnVal = response.isXXX();
    return returnVal;
}  

Now follwoing is the test

@Test
public void testmethod() throws Exception{
    //arrange
    String userName = "UserName";
    ClassA request = new ClassA();
    ClassB response = new ClassB();
    response.setXXX(true);
    when(stub.callingmethod(request)).thenReturn(response);
    //act
    boolean result = fooinstance.lockLogin(userName);

    //assert
    assertTrue(result);
}

stub is mocked using mockito i.e using @Mock. The test throws NullPointerException in class foo near boolean retrunVal = response.isXXX();

2

2 Answers

8
votes

the argument matcher for stub.callingmethod(request).thenReturn(response) is comparing for reference equality. You want a more loose matcher, like this I think:

stub.callingmethod(isA(ClassA.class)).thenReturn(response);
0
votes

Ensure that your ClassA implements its own equals and that it is correctly implemented.