Search code examples
javaspringjunitmockitospringmockito

Mockito when() method not working and getting null pointer exception


I am writing unit test cases using Mockito and JUnit . But getting NullPointerException when running a test. On debugging I get to know that Mockito on method: when().thenReturn() is not returning a value for dependent methods and the calling program is calling those methods to get result.

Below is my dummy code to get idea of structure of code:

class B {
  public C getValue() {
    return C;
  }
}

class A {
  public D getAns(String q1, String q2) {
    return B.getValue().map(mapper::toD); //null pointer exception start here 
  } 
}

@RunWith(MockitoJunitrunner.test)
class TestA {
  
  @InjectMock
  A a;

  @Mock
  B b;
  C c;

  init() {
    when(b.getValue()).thenReturn(c);
  }

  @Test
  public void getA() {
    D ans=A.getAns(q1,q2);  //getting null pointer exception here 
    AssertNotNull(ans);
  }
}

Solution

  • You have classes calling each others methods so it is better to use Mockito.RETURNS_DEEP_STUBS

    In your Case:

    A is calling B and B is calling C

    Just replace:

     @InjectMock
      A a;
    
      @Mock
      B b;
      C c;
    

    With :

    A a = Mockito.mock(A.class, Mockito.RETURNS_DEEP_STUBS);
    B b = Mockito.mock(B.class, Mockito.RETURNS_DEEP_STUBS);
    C c = Mockito.mock(C.class, Mockito.RETURNS_DEEP_STUBS);