一尘不染

@Autowired对象仅在测试时为空

spring-boot

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

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

应用程序

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

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

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

package metrics;

import com.blakeparmeter.metricsapi.Application;
import com.blakeparmeter.metricsapi.api.MetricAPI;
import com.blakeparmeter.metricsapi.beans.Metric;
import com.fasterxml.jackson.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

<?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>

堆栈跟踪:

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)

阅读 262

收藏
2020-05-30

共1个答案

一尘不染

standaloneSetup用于单元测试。但是似乎您正在执行集成测试,因此以下代码应该可以工作-我尚未测试过。

更换

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

@Autowired
private WebApplicationContext wac;

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

并将其添加到您的测试班级:

@WebAppConfiguration

奖金

@RunWith(SpringRunner.class)告诉JUnit使用Spring的测试支持运行。SpringRunner是SpringJUnit4ClassRunner的新名称,在眼睛上稍微容易一点。

2020-05-30