简体   繁体   中英

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 ie using @Mock. The test throws NullPointerException in class foo near boolean retrunVal = response.isXXX();

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM