【发布时间】:2016-12-21 02:51:42
【问题描述】:
有一个非常轻量级的 Spring Boot 1.4 项目,从 start.spring.io 生成。
尝试使用TestRestTemplate 对@RestController 和@RequestBody 运行集成测试,但由于启动异常而没有成功。
唯一的配置类:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
配置文件application.properties 几乎没有,除了security.ignored=/** 用于测试目的。
测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
@DataJpaTest
public class MyControllerTest {
private Logger log = Logger.getLogger(getClass());
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private TestEntityManager entityManager;
@Before
public void init() {
log.info("Initializing...");
}
@Test
public void addTest() throws Exception {
log.info("MyController add test starting...");
// restTemplate usage
log.info("MyController add test passed");
}
}
...但是在测试启动过程中出现以下异常:
ERROR 6504 --- [ main] o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.AutoConfigureReportTestExecutionListener@5444f1c3] to prepare test instance [com.myproject.controllers.MyControllerTest@5d2bc446]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.myproject.controllers.MyControllerTest': Unsatisfied dependency expressed through field 'restTemplate': No qualifying bean of type [org.springframework.boot.test.web.client.TestRestTemplate] found for dependency [org.springframework.boot.test.web.client.TestRestTemplate]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.boot.test.web.client.TestRestTemplate] found for dependency [org.springframework.boot.test.web.client.TestRestTemplate]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
根据doc,不需要在任何地方配置TestRestTemplate。不过,我已按照建议将最新的 Apache Http Client 添加到类路径中。
我错过了什么?
【问题讨论】:
-
刚刚发现
@AutoConfigureTestDatabase注解应该和@SpringBootTest一起使用,而不是@DataJpaTest在这种情况下
标签: java spring exception spring-boot autowired