有一個很輕的Spring Boot 1.4項目,從start.spring.io生成。Spring Boot 1.4 - TestRestTemplate不滿意的依賴異常
嘗試使用TestRestTemplate
運行@RestController
與@RequestBody
的集成測試,但由於啓動異常而沒有成功。
唯一的配置類:
配置文件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.b[email protected]5444f1c3] to prepare test instance [[email protected]]
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'的情況下喜歡這個 – WildDev