java-@Autowired对象仅在测试时为空
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-@Autowired对象仅在测试时为空,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含7786字,纯文字阅读大概需要12分钟。
内容图文
![java-@Autowired对象仅在测试时为空](/upload/InfoBanner/zyjiaocheng/696/cf10b45c09d6464095c443d7375f76a7.jpg)
我的问题与应用程序设置有关,而不是模拟或使用自动装配.有关更多详细信息,请参见答案.
我正在尝试建立一个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)
解决方法:
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) 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.
内容总结
以上是互联网集市为您收集整理的java-@Autowired对象仅在测试时为空全部内容,希望文章能够帮你解决java-@Autowired对象仅在测试时为空所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。