Spring Boot中单元测试中的@Autowired返回NullPointerException。

huangapple go评论101阅读模式
英文:

Spring Boot @Autowired in unit test returns NullPointerException

问题

I have a class(HttpHandler) annotated with @service. I'm writing unit test case for this service class.
我有一个使用 @service 注解的类(HttpHandler)。我正在为这个服务类编写单元测试用例。

I used @Autowired annotation in my test class to get the object of the service. However, When I run the unit test it return NullPointerException. Can someone help me?
我在我的测试类中使用了 @Autowired 注解来获取服务对象。然而,当我运行单元测试时,它返回了NullPointerException。有人能帮助我吗?

Below is the code of the service class:
以下是服务类的代码:

  1. @Service
  2. public class HttpHandler {
  3. private static final Logger logger = LoggerFactory.getLogger(HttpHandler.class);
  4. /**
  5. * Build the request and Perform Http Get request with headers
  6. * @param url
  7. * @param httpHeaders
  8. * @param responseClass
  9. * @param <T>
  10. * @param <R>
  11. * @return
  12. */
  13. public <T,R> ResponseEntity<T> sendPost(String url, HttpHeaders httpHeaders, R requestBody, Class<T> responseClass) {
  14. //create an instance of rest template
  15. RestTemplate restTemplate = new RestTemplate();
  16. HttpEntity<R> entity = new HttpEntity<R>(requestBody, httpHeaders);
  17. logger.info("POST request to " + url + " with body: " + JsonUtil.jsonizeExcludeNulls(requestBody));
  18. //make an HTTP POST request with headers
  19. ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.POST, entity, responseClass);
  20. logger.info("POST" + url + ": " + JsonUtil.jsonize(response));
  21. return response;
  22. }
  23. }

I'm writing unit test case for POST call. Below is the unit test for POST call
我正在编写POST调用的单元测试用例。以下是用于POST调用的单元测试:

  1. public class HttpHandlerTest {
  2. @Autowired
  3. HttpHandler httpHandler;
  4. @Test
  5. public void testSuccessPostUser() throws Exception{
  6. String baseUrl = "http://localhost:8080/users";
  7. List<String> messages = new ArrayList<>();
  8. messages.add("Hi");
  9. User user = new User();
  10. user.setId(1);
  11. user.setName("John");
  12. user.setAge(22);
  13. user.setMessages(messages);
  14. HttpHeaders httpHeaders = new HttpHeaders();
  15. httpHeaders.setContentType(MediaType.APPLICATION_JSON);
  16. httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
  17. HttpEntity<User> httpEntity = new HttpEntity<>(user, httpHeaders);
  18. ResponseEntity<User> actual = httpHandler.sendPost(baseUrl, httpHeaders, user, User.class);
  19. //verify request succeed
  20. assertEquals(HttpStatus.CREATED, actual.getStatusCode());
  21. assertEquals(201, actual.getStatusCodeValue());
  22. assertTrue(actual.toString().contains("id"));
  23. }
  24. }

It gives below error:
它报以下错误:

  1. java.lang.NullPointerException
  2. at com.xyz.provisioning.xyz.utils.HttpHandlerTest.testSuccessPostUser(HttpHandlerTest.java:41)
  3. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  4. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  5. at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  6. at java.base/java.lang.reflect.Method.invoke(Method.java:566)
  7. at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
  8. at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
  9. at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
  10. at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
  11. at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
  12. at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
  13. at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
  14. at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
  15. at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
英文:

I have a class(HttpHandler) annotated with @service. I'm writing unit test case for this service class.
I used @Autowired annotation in my test class to get the object of the service. However, When I run the unit test it return NullPOinterException. Can someone help me?

Below is the code of service class:

  1. @Service
  2. public class HttpHandler {
  3. private static final Logger logger = LoggerFactory.getLogger(HttpHandler.class);
  4. /**
  5. * Build the request and Perform Http Get request with headers
  6. * @param url
  7. * @param httpHeaders
  8. * @param responseClass
  9. * @param &lt;T&gt;
  10. * @param &lt;R&gt;
  11. * @return
  12. */
  13. public &lt;T,R&gt; ResponseEntity&lt;T&gt; sendPost(String url, HttpHeaders httpHeaders, R requestBody, Class&lt;T&gt; responseClass) {
  14. //create an instance of rest template
  15. RestTemplate restTemplate = new RestTemplate();
  16. HttpEntity&lt;R&gt; entity = new HttpEntity&lt;R&gt;(requestBody, httpHeaders);
  17. logger.info(&quot;POST request to &quot; + url + &quot; with body: &quot; + JsonUtil.jsonizeExcludeNulls(requestBody));
  18. //make an HTTP POST request with headers
  19. ResponseEntity&lt;T&gt; response = restTemplate.exchange(url, HttpMethod.POST, entity, responseClass);
  20. logger.info(&quot;POST&quot; + url + &quot;: &quot; + JsonUtil.jsonize(response));
  21. return response;
  22. }
  23. }

I'm writing unit test case for POST call. Below is the unit test for POST call
public class HttpHandlerTest {

  1. @Autowired
  2. HttpHandler httpHandler;
  3. @Test
  4. public void testSuccessPostUser() throws Exception{
  5. String baseUrl = &quot;http://localhost:8080/users&quot;;
  6. List&lt;String&gt; messages = new ArrayList&lt;&gt;();
  7. messages.add(&quot;Hi&quot;);
  8. User user = new User();
  9. user.setId(1);
  10. user.setName(&quot;John&quot;);
  11. user.setAge(22);
  12. user.setMessages(messages);
  13. HttpHeaders httpHeaders = new HttpHeaders();
  14. httpHeaders.setContentType(MediaType.APPLICATION_JSON);
  15. httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
  16. HttpEntity&lt;User&gt; httpEntity = new HttpEntity&lt;&gt;(user, httpHeaders);
  17. ResponseEntity&lt;User&gt; actual = httpHandler.sendPost(baseUrl, httpHeaders, user, User.class);
  18. //verify request succeed
  19. assertEquals(HttpStatus.CREATED, actual.getStatusCode());
  20. assertEquals(201, actual.getStatusCodeValue());
  21. assertTrue(actual.toString().contains(&quot;id&quot;));
  22. }

}

It gives below error:

  1. java.lang.NullPointerException
  2. at com.xyz.provisioning.xyz.utils.HttpHandlerTest.testSuccessPostUser(HttpHandlerTest.java:41)
  3. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  4. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  5. at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  6. at java.base/java.lang.reflect.Method.invoke(Method.java:566)
  7. at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
  8. at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
  9. at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
  10. at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
  11. at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
  12. at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
  13. at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
  14. at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
  15. at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)

答案1

得分: 3

  1. 对于JUnit 5如评论中所提到的),您只需在测试类的顶部添加`@SpringBootTest`注解
  2. ```java
  3. @SpringBootTest
  4. class HttpHandlerTest{
  5. // ...
  6. }

不需要添加@ExtendWith(SpringExtension.class),因为它会被@SpringBootTest注解自动导入。

要在JUnit 4中获得相同的结果:

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. class HttpHandlerTest{
  4. // ...
  5. }
  1. <details>
  2. <summary>英文:</summary>
  3. For Junit 5 (as mentioned in the comments) you just need to add `@SpringBootTest` on top of the test class.
  4. ```java
  5. @SpringBootTest
  6. class HttpHandlerTest{
  7. // ...
  8. }

You don't need to add @ExtendWith(SpringExtension.class) because is automatically imported by the annotation @SpringBootTest.

To get the same result for Junit 4:

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. class HttpHandlerTest{
  4. // ...
  5. }

答案2

得分: 2

在类上面添加@ExtendWith(SpringExtension.class),如果你使用JUnit5,或者添加@RunWith(SpringRunner.class),如果你使用JUnit4。

英文:

Add @ExtendWith(SpringExtension.class) above the class if you're using JUnit5 or @RunWith(SpringRunner.class) if you're using JUnit4.

huangapple
  • 本文由 发表于 2020年7月31日 12:56:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63186010.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定