Mockito when() 方法不起作用并出现空指针异常

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

我正在使用 Mockito 和 JUnit 编写单元测试用例。但是得到NullPointerException当运行一个测试。在调试时,我了解到 Mockito on method: when().thenReturn() 没有返回依赖方法的值,调用程序正在调用这些方法来获取结果。

下面是我用来了解代码结构的虚拟代码:

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

when(...).thenReturn(...) 未被调用的原因可能有多种:

  1. when 构造中使用的数据类型不完全匹配,例如,如果您有一个字符串并传递 null,则它不是同一个方法调用
  2. 确保使用相同的方法初始化对象。 spring 注入的资源与使用 new operator
  3. 创建的资源不同

你们 类 调用了彼此的方法,所以最好使用 Mockito.RETURNS_DEEP_STUBS

你的案例:

A is calling B and B is calling C

只需替换:

 @InjectMock
  A a;

  @Mock
  B b;
  C c;

有:

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

使用@InjectMock 和@Mock 解决这个问题