简体   繁体   English

Mockito when() 方法不工作并得到 null 指针异常

[英]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.我正在使用 Mockito 和 JUnit 编写单元测试用例。但是在运行测试时出现NullPointerException 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.在调试时,我了解到 Mockito on method: when().thenReturn()没有返回依赖方法的值,调用程序正在调用这些方法以获得结果。

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

There may be multiple reason to why when(...).thenReturn(...) is not called :不调用when(...).thenReturn(...)原因可能有多种:

  1. The data type which is used in when construct is not matching exact, for example, if you have a string and you pass null, its not same method call构造中使用的数据类型不完全匹配,例如,如果您有一个字符串并且您传递 null,则其方法调用不相同
  2. Ensure that the objects are getting initialized using the same approach.确保使用相同的方法初始化对象。 A spring injected resource is not same as the one created using new operator spring 注入的资源与使用 new 运算符创建的资源不同

You have classes calling each others methods so it is better to use Mockito.RETURNS_DEEP_STUBS你有类调用彼此的方法,所以最好使用Mockito.RETURNS_DEEP_STUBS

In your Case:在您的情况下:

A is calling B and B is calling C A呼叫BB呼叫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);

use @InjectMock and @Mock to solve this issue使用@InjectMock 和@Mock 来解决这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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