简体   繁体   English

NullpointerException mocking 测试

[英]NullpointerException mocking the test

I have a problem mocking the test, everything goes correct till this point of the code/test which i get a NullPointerException , this is the main code where launches the null pointer.我有一个问题 mocking 测试,一切正常,直到我得到NullPointerException的代码/测试点,这是启动 null 指针的主要代码。

ResponseSrvAddDto responseSrvAdd = kjidR048.executeAddDocuments(requestAdd);
        
String returnCode = responseSrvAdd.getReturnCode();
if (returnCode != null && "00".equals(returnCode)){
ERROR! java.lang.NullPointerException

I have this in the test我在测试中有这个

ResponseSrvAddDto responseSrvAdd = mock(ResponseSrvAddDto.class);

Mockito.when(kjidR048.executeAddDocuments(requestAdd)).thenReturn(responseSrvAdd); (this goes correct)
String code = "00";
Mockito.when(responseSrvAdd.getReturnCode()).thenReturn(code); 

(but this looks like ignores the mock) (但这看起来像忽略了模拟)

I don't know why having the mock in the responseSrvAdd.getReturnCode() launches a null pointer but i have this already mocked.我不知道为什么在responseSrvAdd.getReturnCode()中有模拟会启动一个 null 指针,但我已经对此进行了模拟。

When you use mock on service it's create a object that do nothing or return null on all method.当您在服务上使用模拟时,它会创建一个 object 什么都不做或在所有方法上返回 null。 If you want to test responseSrvAdd.getReturnCode() use spy https://www.baeldung.com/mockito-spy here is guide.如果你想测试responseSrvAdd.getReturnCode()使用 spy https://www.baeldung.com/mockito-spy这里是指南。

For entity you need to create object it will be like this:对于需要创建 object 的实体,它将如下所示:

ResponseSrvAddDto responseSrvAdd = new ResponseSrvAddDto(); ResponseSrvAddDto responseSrvAdd = new ResponseSrvAddDto(); responseSrvAdd.setReturnCode("00"); responseSrvAdd.setReturnCode("00"); Mockito.when(kjidR048.executeAddDocuments(requestAdd)).thenReturn(responseSrvAdd); Mockito.when(kjidR048.executeAddDocuments(requestAdd)).thenReturn(responseSrvAdd);

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

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