Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mockito stubbing returns null

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();

like image 628
Ritesh Mengji Avatar asked Feb 25 '23 00:02

Ritesh Mengji


1 Answers

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);
like image 62
Kevin Avatar answered Mar 04 '23 07:03

Kevin