Junit單元測試Spring 讀取WEB-INF下的配置文件


轉載地址:http://www.mrfeng.net/post/189.html

假設Spring配置文件為applicationContext.xml


一、Spring配置文件在類路徑下面

在Spring的java應用程序中,一般我們的Spring的配置文件都是放在放在類路徑下面(也即編譯后會進入到classes目錄下)。

以下是我的項目,因為是用maven管理的,所以配置文件都放在“src/main/resources”目錄下

 

這時候,在代碼中可以通過

[java] view plain copy
  1. ApplicationContext applicationContext = newClassPathXmlApplicationContext("applicationContext.xml");  

然后獲取相應的bean。

 

如果代碼想用Junit測試框架來測試,則Spring提供了對Junit支持,還可以使用注解的方式:

[java] view plain copy
  1. @RunWith(SpringJUnit4ClassRunner.class)  

  2. @ContextConfiguration(locations={"classpath:applicationContext.xml"})  

只需要在相應的Test類前面加上此兩個注解(第二個注解用來指明Spring的配置文件位置),就可以在Junit Test類使用中Spring提供的依賴注入功能。

 

二、Spring配置文件在WEB-INF下面

當然在做J2EE開發時,有些人習慣把Spring文件放在WEB-INF目錄(雖然更多人習慣放在類路徑下面)下面;或者有些Spring配置文件是放在類路徑下面,而有些又放在

WEB-INF目錄下面,如下圖。

這時候,在代碼中就不可以使用ClassPathXmlApplicationContext來加載配置文件了,而應使用FileSystemXmlApplicationContext。

[java] view plain copy
  1. ApplicationContext applicationContext = newFileSystemXmlApplicationContext("src/main/webapp/WEB-INF/applicationContext.xml");  

然后獲取相應的bean。

 

如果代碼想用Junit測試框架來測試,則Spring提供了對Junit支持,還可以使用注解的方式:

[java] view plain copy
  1. @RunWith(SpringJUnit4ClassRunner.class)  

  2. @ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/applicationContext.xml"})  

只需要在相應的Test類前面加上此兩個注解(第二個注解用來指明Spring的配置文件位置),就可以在Junit Test類使用中Spring提供的依賴注入功能。

 

下面是我的一個Spring管理下的Junit測試類:

[java] view plain copy
    1. package com.sohu.group.service.external;  

    2.  

    3. import java.util.List;  

    4.  

    5. import org.junit.Test;  

    6. import org.junit.runner.RunWith;  

    7. import org.springframework.beans.factory.annotation.Autowired;  

    8. import org.springframework.test.context.ContextConfiguration;  

    9. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  

    10.  

    11. @RunWith(SpringJUnit4ClassRunner.class)  

    12. @ContextConfiguration({"file:src/main/webapp/WEB-INF/applicationContext.xml"})  

    13. public class SuFriendServiceImplOverRMITest {  

    14.  

    15.    @Autowired  

    16.    private SuFriendService suFriendService;  

    17.      

    18.    @Test  

    19.    public void getUserFollowerListTest(){  

    20.        List<String> list = suFriendService.getUserFollowerList("liug_talk@163.com");  

    21.        System.out.println("------"+list);  

    22.    }  

    23. }  


免責聲明!

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



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