SpringBoot中Junit測試注入Bean失敗的解決方法

在SpringBoot中使用Junit做測試的時候測試DAO層的接口,但是一直提示注入Bean失敗,報以下錯誤:


org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'hellowood.TestFeedbackMapper': Unsatisfied dependency expressed through field 'feedbackDetailMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'hellowood.lntu.oe.wmp.dao.FeedbackDetailMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}


在查詢了其他項目的Junit後發現Junit的註解是這樣的


@RunWith(SpringJUnit4Cla***unner.class)

@SpringApplicationConfiguration(classes = Application.class)

@WebAppConfiguration


而新建的項目中是這樣的


@RunWith(SpringRunner.class)

@SpringBootTest

@WebAppConfiguration


直接修改註解後發現不能引入SpringApplicationConfiguration,而所有的依賴只是版本不一樣,查閱了Spring官方文檔後發現新版中用SpringBootTest代替了SpringApplicationConfiguration,所以將註解改爲以下形式就可以正常注入Bean了


@RunWith(SpringRunner.class)

@SpringBootTest(classes = Application.class)

@WebAppConfiguration

歡迎工作一到五年的Java工程師朋友們加入Java技術交流羣:659270626
羣內提供免費的Java架構學習資料(裏面有高可用、高併發、高性能及分佈式、Jvm性能調優、Spring源碼,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多個知識點的架構資料)合理利用自己每一分每一秒的時間來學習提升自己,不要再用"沒有時間“來掩飾自己思想上的懶惰!趁年輕,使勁拼,給未來的自己一個交代!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章