英文:
Mockito when() method not working and getting null pointer exception
问题
以下是翻译好的内容:
我正在使用Mockito和JUnit编写单元测试案例。但在运行测试时出现了NullPointerException
。经过调试,我了解到在Mockito的方法when().thenReturn()
中,对于依赖方法未返回值,而调用程序正在调用这些方法以获取结果。
以下是我用来了解代码结构的示例代码:
class B {
public C getValue() {
return C;
}
}
class A {
public D getAns(String q1, String q2) {
return B.getValue().map(mapper::toD); // 空指针异常从这里开始
}
}
@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); // 这里出现空指针异常
AssertNotNull(ans);
}
}
英文:
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:
<!-- language: java -->
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);
}
}
答案1
得分: 1
可能有多个原因解释为什么 when(...).thenReturn(...)
没有被调用:
- 在
when
结构中使用的数据类型不匹配,例如,如果你有一个字符串而你传递了null,这不是相同的方法调用。 - 确保对象是使用相同的方法进行初始化的。通过Spring注入的资源与使用
new
操作符创建的资源并不相同。
英文:
There may be multiple reason to why when(...).thenReturn(...)
is not called :
- 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
- 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
答案2
得分: 1
你有类相互调用方法的情况,因此最好使用Mockito.RETURNS_DEEP_STUBS
。
在你的情况下:
> A
正在调用B
,而B
正在调用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);
英文:
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);
答案3
得分: 0
使用 @InjectMock 和 @Mock 来解决这个问题。
英文:
use @InjectMock and @Mock to solve this issue
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论