Spring Boot @Autowired in unit test returns NullPointerException(单元测试中的SpringBoot@Auowired返回NullPointerException)
问题描述
我有一个用@SERVICE注释的类(HttpHandler)。我正在为这个服务类编写单元测试用例。 我在我的测试类中使用了@AuTower注释来获取服务的对象。然而,当我运行单元测试时,它返回NullPOinterException。有人能帮帮我吗?
服务等级代码如下:
@Service
public class HttpHandler {
private static final Logger logger = LoggerFactory.getLogger(HttpHandler.class);
/**
* Build the request and Perform Http Get request with headers
* @param url
* @param httpHeaders
* @param responseClass
* @param <T>
* @param <R>
* @return
*/
public <T,R> ResponseEntity<T> sendPost(String url, HttpHeaders httpHeaders, R requestBody, Class<T> responseClass) {
//create an instance of rest template
RestTemplate restTemplate = new RestTemplate();
HttpEntity<R> entity = new HttpEntity<R>(requestBody, httpHeaders);
logger.info("POST request to " + url + " with body: " + JsonUtil.jsonizeExcludeNulls(requestBody));
//make an HTTP POST request with headers
ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.POST, entity, responseClass);
logger.info("POST" + url + ": " + JsonUtil.jsonize(response));
return response;
}
}
我正在为POST调用编写单元测试用例。下面是POST调用的单元测试 公共类HttpHandlerTest{
@Autowired
HttpHandler httpHandler;
@Test
public void testSuccessPostUser() throws Exception{
String baseUrl = "http://localhost:8080/users";
List<String> messages = new ArrayList<>();
messages.add("Hi");
User user = new User();
user.setId(1);
user.setName("John");
user.setAge(22);
user.setMessages(messages);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<User> httpEntity = new HttpEntity<>(user, httpHeaders);
ResponseEntity<User> actual = httpHandler.sendPost(baseUrl, httpHeaders, user, User.class);
//verify request succeed
assertEquals(HttpStatus.CREATED, actual.getStatusCode());
assertEquals(201, actual.getStatusCodeValue());
assertTrue(actual.toString().contains("id"));
}
}
它显示以下错误:
java.lang.NullPointerException
at com.xyz.provisioning.xyz.utils.HttpHandlerTest.testSuccessPostUser(HttpHandlerTest.java:41)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
推荐答案
对于JUNIT 5(如注释中所述),您只需在测试类的顶部添加@SpringBootTest
。
@SpringBootTest
class HttpHandlerTest{
// ...
}
您不需要添加@ExtendWith(SpringExtension.class)
,因为是由批注@SpringBootTest
自动导入的。
要获得与Junit4相同的结果:
@RunWith(SpringRunner.class)
@SpringBootTest
class HttpHandlerTest{
// ...
}
这篇关于单元测试中的SpringBoot@Auowired返回NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:单元测试中的SpringBoot@Auowired返回NullPointerExcepti
基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01