首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >单元测试中的Spring @Autowired返回NullPointerException

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

Stack Overflow用户
提问于 2020-07-31 04:56:44
回答 2查看 6.6K关注 0票数 1

我有一个用@service注释的类(HttpHandler)。我正在为这个服务类编写单元测试用例。我在我的测试类中使用了@Autowired注释来获取服务的对象。但是,当我运行单元测试时,它返回NullPOinterException。有人能帮我吗?

以下是服务类的代码:

代码语言:javascript
运行
复制
@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 call公共类HttpHandlerTest {的单元测试

代码语言:javascript
运行
复制
@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"));
}

}

它给出了以下错误:

代码语言:javascript
运行
复制
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)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-07-31 08:10:05

对于Junit 5(如注释中提到的),只需在测试类的顶部添加@SpringBootTest即可。

代码语言:javascript
运行
复制
@SpringBootTest
class HttpHandlerTest{
// ...
}

您不需要来添加@ExtendWith(SpringExtension.class),因为注释@SpringBootTest是自动导入的。

要获得Junit 4的相同结果,请执行以下操作:

代码语言:javascript
运行
复制
@RunWith(SpringRunner.class)
@SpringBootTest
class HttpHandlerTest{
// ...
}
票数 3
EN

Stack Overflow用户

发布于 2020-07-31 07:33:31

如果使用的是@ExtendWith(SpringExtension.class),则在类的前面添加JUnit5,如果使用JUnit4,则添加@RunWith(SpringRunner.class)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63186010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档