我的问题与应用程序设置有关,而不是嘲笑或使用自动装配。有关详细信息,请参阅答案。
我试图设置一个Spring Boot应用程序,但我在创建单元测试时遇到了问题。我的问题是,我所拥有的所有对象@Autowired
仅在单元测试期间为空。当我正常运行应用程序时,我可以使用CURL并且它可以工作。但是,当我使用JUnit进行测试时,当我尝试使用@Autowired
对象时,我得到一个空指针。我没有使用xml文件来配置我的bean,也许这是我的问题?
Application.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
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)
答案 0 :(得分:8)
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的新名称, 它的眼睛更容易一点。