我愛Java系列---【 Spring 整合 Junit : Spring-test】


目的:

在測試類中,每個測試方法都有以下兩行代碼:

 

ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");

IAccountService accountService = ac.getBean("accountService",IAccountService.class);

 

這兩行代碼的作用是獲取容器,如果不寫的話,直接會提示空指針異常。所以又不能輕易刪掉。

所以用在pom.xml文件中導入spring-test依賴,可以把這兩句話封裝到spring框架中,方便我們之后的調用。

步驟:

1.在pom.xml文件中導入spring-context。

  <!-- spring框架 -->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.2.RELEASE</version>注意版本要與spring-test的版本一致
  </dependency>

 

2.在pom.xml文件中導入junit。

 

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version><!--此處需要注意的是,spring5 及以上版本要求 junit 的版本必須是 4.12 及以上,否則用不了-->
      <scope>test</scope>
    </dependency>

 

 

 

 

3.在pom.xml文件中導入 spring 整合 Junit 的坐標----spring-test。

 

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-test</artifactId>
 <version>5.0.2.RELEASE</version>注意版本要與spring-context的版本一致,不一致會報錯。
 </dependency>

 

4.使用@RunWith 注解替換原有運行器

 

/**
* 測試類
* @author 少年攻城獅
* @Version 1.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
public class AccountServiceTest {
}

 

5.使用@ContextConfiguration 指定 spring 配置文件的位置

 

/**
* 測試類
* @author 少年攻城獅
* @Version 1.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
}
@ContextConfiguration 注解:
locations 屬性:用於指定配置文件的位置。如果是類路徑下,需要用 classpath:表明

classes 屬性:用於指定注解的類。當不使用 xml 配置時,需要用此屬性指定注解類的位置,格式: @ContextConfig(classes=Config.class)。

 

6.使用@Autowired 給測試類中的變量注入數據

 

/**
* 測試類
* @author 少年攻城獅
* @Version 1.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
@Autowired
private IAccountService as ;
}

 

問題:為什么不把測試類配到 xml 中?

 

在解釋這個問題之前,先解除大家的疑慮,配到 XML 中能不能用呢?
答案是肯定的,沒問題,可以使用。
那么為什么不采用配置到 xml 中的方式呢?
這個原因是這樣的:
第一:當我們在 xml 中配置了一個 bean,spring 加載配置文件創建容器時,就會創建對象。
第二:測試類只是我們在測試功能時使用,而在項目中它並不參與程序邏輯,也不會解決需求上的問
題,所以創建完了,並沒有使用。那么存在容器中就會造成資源的浪費。
所以,基於以上兩點,我們不應該把測試配置到 xml 文件中。

 


免責聲明!

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



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