java @Autowired 对象仅在测试时为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43128842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:06:42  来源:igfitidea点击:

@Autowired objects are null only when testing

javaspring-bootjunitautowired

提问by Doctor Parameter

My question has to do with the application set-up, not mocking or using autowiring. See the answer for more details.

我的问题与应用程序设置有关,而不是模拟或使用自动装配。有关更多详细信息,请参阅答案。

I'm trying to set up a Spring Boot application and I'm having issues creating unit tests. My issue is that all objects I have @Autowiredare null only during unit testing. When I run the application normally I'm able to use CURL for and it works. However when I test with JUnit I get a null pointer when I try to use the @Autowiredobjects. I am not using a xml file to configure my beans, maybe that is my problem?

我正在尝试设置 Spring Boot 应用程序,但在创建单元测试时遇到问题。我的问题是我拥有的所有对象@Autowired仅在单元测试期间为空。当我正常运行应用程序时,我可以使用 CURL 并且它可以工作。但是,当我使用 JUnit 进行测试时,当我尝试使用这些@Autowired对象时会得到一个空指针。我没有使用 xml 文件来配置我的 bean,也许这是我的问题?

Application.java

应用程序.java

package com.blakeparmeter.metricsapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 *
 * @author Blake
 */
@SpringBootApplication
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }
}

MetricApi.java

MetricApi.java

package com.blakeparmeter.metricsapi.api;

import com.blakeparmeter.metricsapi.beans.Metric;
import com.blakeparmeter.metricsapi.controllers.MetricController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Handles all the REST responses logic of the Metrics services. 
 * Complex logic should be moved outside of this class.
 * @author Blake
 */
@RestController
@EnableAutoConfiguration
public class MetricAPI {

    @Autowired 
    private MetricController metricController;

    @RequestMapping("/addMetric")
    public ResponseEntity<?> addMetric(@RequestBody Metric record){
        metricController.addMetric(record);
        return ResponseEntity.ok().build();
    }
}

MetricController.java

度量控制器.java

package com.blakeparmeter.metricsapi.controllers;

import com.blakeparmeter.metricsapi.beans.Metric;
import org.springframework.stereotype.Controller;

/**
 *
 * @author Blake
 */
@Controller
public class MetricController {

    public Metric addMetric(Metric metric){
        System.out.println("Adding a metric!");
        return metric;
    }
}

MetricsTest.java

指标测试.java

package metrics;

import com.blakeparmeter.metricsapi.Application;
import com.blakeparmeter.metricsapi.api.MetricAPI;
import com.blakeparmeter.metricsapi.beans.Metric;
import com.fasterxml.Hymanson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

/**
 * @author Blake 
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class MetricsTest {

    private MockMvc mockMvc;

    @Autowired
    ObjectMapper objectMapper;

    @Before
    public void setup() throws Exception {
        mockMvc = standaloneSetup(new MetricAPI()).build();
    }

    /**
     * Adds a valid metric
     * @throws Exception 
     */
    @Test
    public void addMetricTest() throws Exception{
        mockMvc.perform(post("/addMetric")
            .contentType(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(new Metric())))
                .andExpect(status().isOk());
    }
}

pom.xml

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.blakeparmeter</groupId>
    <artifactId>MetricsAPI</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
    </dependencies>
</project>

Stack trace:

堆栈跟踪:

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 13.569 sec <<< FAILURE! - in metrics.MetricsTest
addMetricTest(metrics.MetricsTest)  Time elapsed: 0.174 sec  <<< ERROR!
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    at com.blakeparmeter.metricsapi.api.MetricAPI.addMetric(MetricAPI.java:30)
    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)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
    at metrics.MetricsTest.addMetricTest(MetricsTest.java:47)

回答by kkflf

standaloneSetupis used for unit tests. But it seems like you are doing integrations tests, so the below code should work - I have not tested it.

standaloneSetup用于单元测试。但看起来您正在进行集成测试,所以下面的代码应该可以工作 - 我还没有测试过。

Replace

代替

@Before
public void setup() throws Exception {
    mockMvc = standaloneSetup(new MetricAPI()).build();
}

with

@Autowired
private WebApplicationContext wac;

@Before
public void setup() throws Exception {
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}

and add this to your test class:

并将其添加到您的测试类中:

@WebAppConfiguration

Bonus

奖金

@RunWith(SpringRunner.class) tells JUnit to run using Spring's testing support. SpringRunner is the new name for SpringJUnit4ClassRunner, it's just a bit easier on the eye.

@RunWith(SpringRunner.class) 告诉 JUnit 使用 Spring 的测试支持运行。SpringRunner 是 SpringJUnit4ClassRunner 的新名称,它看起来更容易一些。