单元测试给出 NullPointerException
Posted
技术标签:
【中文标题】单元测试给出 NullPointerException【英文标题】:Unit test gives NullPointerException 【发布时间】:2021-01-07 05:36:27 【问题描述】:我正在尝试为 handler.sendRequest(request); 编写一个单元测试用例。功能。但是,它返回空指针异常。 当我在单元测试中打印请求对象时,它返回 null。但是,我已经初始化了请求对象,不确定它为什么给出空指针异常。数据对象有问题吗?我错过了什么吗?有人可以帮忙吗?谢谢!
public class ServicesHandlerTest
@Mock
private RestTemplate restTemplate;
@Mock
private ObjectMapper mapper;
@Mock
private AuthHandler AuthHandler;
@InjectMocks
ServicesHandler handler;
@Before
public void init()
MockitoAnnotations.initMocks(this);
@After
public void tearDown() throws Exception
@Test
public void testSuccess() throws Exception
Data data = new Data();
data.setRequestId(UUID.randomUUID().toString());
data.setRequestedQuantity(10);
Request request = new Request();
request.setData(data );
System.out.println("request = " + request);
ServicesHandler handler = new ServicesHandler();
Mockito.when(AuthHandler.requestToken()).thenReturn("randomString");
Mockito.when(msAuthHandler.createAuthorizationBearerHttpHeaders("randomString")).thenReturn(any());
Mockito.when(restTemplate.postForEntity(anyString(), any(), eq(String.class))).thenReturn(new ResponseEntity<String>(HttpStatus.OK));
handler.sendRequest(request);
@Component
public class ServicesHandler extends AbstractHandler
@Value("$api.host")
private String msApiHost;
@Value("$base.path")
private String BasePath;
@Autowired
private AuthHandler authHandler;
public AuthHandler getAuthHandler()
return authHandler;
public ResponseEntity<String> sendRequest(Request pr) throws Exception
ResponseEntity<String> response = null;
try
String requestToken = getAuthHandler().requestToken();
HttpHeaders headers = getAuthHandler().createAuthorizationBearerHttpHeaders(requestToken);
String apiUrl = ApiHost + BasePath;
RestTemplate restTemplate = new RestTemplate();
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(Include.NON_NULL);
mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);
HttpEntity<Request> request = new HttpEntity<Request>(pr, headers);
response = restTemplate.postForEntity(apiUrl, request, String.class);
catch (HttpStatusCodeException e)
logger.error("Error when sending for provisioning " + e.getResponseBodyAsString(), e);
return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsString());
catch (Exception e)
throw e;
return response;
public class Data
private String requestId;
private Integer requestedQuantity;
public String getRequestId()
return requestId;
public void setRequestId(String requestId)
this.requestId = requestId;
public Integer getRequestedQuantity()
return requestedQuantity;
public void setRequestedQuantity(Integer requestedQuantity)
this.requestedQuantity = requestedQuantity;
它在handler.sendRequest(request);
内的getAuthHandler().requestToken();
函数中给我一个错误
下面是堆栈跟踪:
java.lang.NullPointerException at com.xyz.abc.sendRequest(ServicesHandler.java:443) at com.xyz.abc.ServicesHandlerTest.testSuccess(ServicesHandlerTest.java:150) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498)
【问题讨论】:
您创建模拟,创建处理程序的新实例,但不要将模拟注入处理程序。 @M.Deinum 感谢您的回复。您能否帮助我了解如何将模拟注入处理程序帮助或我该怎么做? 使用@InjectMocks 后还是同样的错误。请协助我修复缺少的内容。 请将堆栈跟踪添加到您的问题中。 java.lang.NullPointerException 在 com.xyz.abc.sendRequest(ServicesHandler.java:443) 在 com.xyz.abc.ServicesHandlerTest.testSuccess(ServicesHandlerTest.java:150) 在 sun.reflect。 NativeMethodAccessorImpl.invoke0(Native Method) 在 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.lang.reflect.Method.invoke(Method. java:498) 【参考方案1】:您应该使用@InjectMocks
将模拟注入ServicesHandler
,有关更多信息,请参阅文档MockitoAnnotations.initMocks
public class ServicesHandlerTest
@InjectMocks
private ServicesHandler;
@Mock
private RestTemplate restTemplate;
@Mock
private ObjectMapper mapper;
@Mock
private AuthHandler AuthHandler;
@Before
public void init()
MockitoAnnotations.initMocks(this);
@After
public void tearDown() throws Exception
@Test
public void testSuccess() throws Exception
Data data = new Data();
data.setRequestId(UUID.randomUUID().toString());
data.setRequestedQuantity(10);
Request request = new Request();
request.setData(data );
System.out.println("request = " + request);
Mockito.when(AuthHandler.requestToken()).thenReturn("randomString");
Mockito.when(restTemplate.postForEntity(anyString(), any(), eq(String.class))).thenReturn(new ResponseEntity<String>(HttpStatus.OK));
handler.sendRequest(request);
【讨论】:
感谢您的帮助!我试过@Injectmocks 但是,它仍然给我一个空指针异常。如果我遗漏了什么,你能帮帮我吗? 我是否遗漏了 requestToken 的某些内容? 你忘了使用跑步者,比如@RunWith(MockitoJUnitRunner.class) @Milgo 我添加了@RunWith(MockitoJunitRunner.class)
仍然是同样的错误。
@Milgo 只是想知道。加跑步者需要什么?以上是关于单元测试给出 NullPointerException的主要内容,如果未能解决你的问题,请参考以下文章
来自 .properties 文件的 Spring Boot 单元测试 @Value 给出 NullPointerException