[英]Mockito.mock is not working, using Mockito.when causes NullPointerException
I have used Mockito very long time.我已经使用 Mockito 很长时间了。 With Mockito 4.7.0 version (and also for example with the version 3.12.4) the code:使用 Mockito 4.7.0 版本(以及例如版本 3.12.4),代码:
A a = mock(A.class);
when(a.doX()).thenReturn("X");
causes the java.lang.NullPointerException
in the second line.导致java.lang.NullPointerException
在第二行。
When I print the content of the variable a
当我打印变量a
的内容时
System.out.println(a);
I got also "java.lang.NullPointerException".我也得到了“java.lang.NullPointerException”。
For any other class the Mockito.mock
and Mockito.when
are working perfectly and if I print a content of some other class instance b
I got "Mock for B, hashcode: some hash code" For any other class the Mockito.mock
and Mockito.when
are working perfectly and if I print a content of some other class instance b
I got "Mock for B, hashcode: some hash code"
Do you know what could be problem?你知道可能是什么问题吗? My example is simplified and I can't show the actual classes.我的示例被简化了,我无法显示实际的类。
I don't have your code, but I tried to be the more generic as I can.我没有你的代码,但我尽量做到更通用。 I have test like the one below and it works great.我有像下面这样的测试,效果很好。 Hope to been helpful.希望能有所帮助。
@ExtendWith(MockitoExtension.class)
class MyTest {
@Mock
private AClass aclass;
@Mock
private BClass bclass;
@Mock
private CClass cclass;
@Test
void testExecute() {
when(aclass.getAbc(any(String.class), any(Date.class), anyString()))
.thenAnswer(i -> getAbc(i.getArgument(0), i.getArgument(1), i.getArgument(2)));
when(bclass.isOk())
.thenAnswer(i -> false);
when(cclass.getCdf(anyString()))
.thenAnswer(i -> getCdf());
...
...
...
}
private List<ABC> getAbc(final String myString, final Date now, final String x) {
...
...
...
}
private CDF getCdf() {
...
...
...
}
}
As you can see, for a simple answer I write the answer directly, for a more complex one, I create a private method with the same name and use it as answer.如您所见,对于一个简单的答案,我直接写答案,对于更复杂的答案,我创建一个具有相同名称的私有方法并将其用作答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.