java - Spring Boot @Autowired 在单元测试中返回 NullPointerException

标签 java spring-boot unit-testing junit resttemplate

我有一个用@service注释的类(HttpHandler)。我正在为此服务类编写单元测试用例。 我在测试类中使用@Autowired注释来获取服务的对象。但是,当我运行单元测试时,它返回 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 调用的单元测试 公共(public)类 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自动导入的。

要为 Junit 4 获得相同的结果:

@RunWith(SpringRunner.class)
@SpringBootTest
class HttpHandlerTest{
// ...
}

关于java - Spring Boot @Autowired 在单元测试中返回 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63186010/

相关文章:

java - 如何在java中解析基于时间的标记?(1m 1M 1d 1Y 1W 1S)

java - 如何计算某个项目在列表中出现的次数

java - 除了基于 token 的身份验证之外,还允许 Rest api 端点使用 http 基本身份验证

javascript - 使用 Typescript 和 Angular 2 进行 Karma 测试会抛出 "System.config"的 Typeerror

java - 在 3 维空间中移动所有点而不存储所有可能的坐标

java - 隐藏敏感信息作为回应

spring-boot - spring boot RedisTemplate配置集群写对象很慢,如果单机很快,为什么?

unit-testing - 在 Dart 中,如何在单元测试中验证不抛出异常的 void 方法?

java - 如何在 Mockito 中编写 if-else 测试用例

java - 从 eclipse 运行时,Maven 不会在项目目录中查找 web.xml