Junit問題01 利用 @Autowired 注入失效問題


 

1 利用 @Autowired 注入失效問題 

  1.1 問題描述

    在使用Junit作為測試框架的單元測試中,直接了用@Autowired記性依賴注入時總是注入失敗

  1.2 問題原因

    在測試類中沒有設定上下文的配置文件信息,指定運行環境為Spring環境

@RunWith就是一個運行器

@RunWith(JUnit4.class)就是指用JUnit4來運行

@RunWith(SpringJUnit4ClassRunner.class),讓測試運行於Spring測試環境

@RunWith(Suite.class)的話就是一套測試集合,


@ContextConfiguration Spring整合JUnit4測試時,使用注解引入多個配置文件


單個文件 

@ContextConfiguration(Locations="classpath:applicationContext.xml")  
@ContextConfiguration(classes = SimpleConfiguration.class)


多個文件時,可用{}

@ContextConfiguration(locations = { "classpath:spring1.xml", "classpath:spring2.xml" }) 
View Code

  1.3 問題解決

    在測試類上添加下面兩行注解

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})

    技巧01:applicationContext.xml 是一個配置bean的文件

    技巧02:juni框架的版本至少是4.12


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM