Spring整合junit測試
阿新 • • 發佈:2017-12-24
幫我 con 如果 註入 很多 創建 由於 spring配置 pan
本節內容:
- Spring整合junit測試的意義
- Spring整合junit測試
一、Spring與整合junit測試的意義
在沒整合junit之前,我們在寫測試方法時,需要在每個方法中手動創建容器,獲取對象,比如下面的代碼,紅色部分都是重復的代碼。如果要測試很多功能的話,每次都得手動去創建容器,很麻煩。如果你測試的兩個功能中用到某個相同的對象,獲取對象的代碼也得寫一遍。
public class test { @Test public void test1(){ //1.創建容器對象(創建Spring的工廠類) ApplicationContext ac = new ClassPathXmlApplicationContext("com/wisedu/annotation/applicationContext.xml"); //ClassPathXmlApplicationContext(從類路徑下加載xml的Application容器)是org.springframework.context.ApplicationContext的實現類 //2.向容器"要"User對象(通過工廠解析XML獲取Bean實例) User user = (User)ac.getBean("user");//3.打印User對象 System.out.print(user); } @Test public void test2(){ //1.創建容器對象(創建Spring的工廠類) ApplicationContext ac = new ClassPathXmlApplicationContext("com/wisedu/annotation/applicationContext.xml"); //ClassPathXmlApplicationContext(從類路徑下加載xml的Application容器)是org.springframework.context.ApplicationContext的實現類 //2.向容器"要"User對象(通過工廠解析XML獲取Bean實例) User user = (User)ac.getBean("user"); User user2 = (User)ac.getBean("user"); User user3 = (User)ac.getBean("user"); //3.打印User對象 System.out.print(user==user2); } }
Spring比較體貼,Spring可以整合Junit測試,使用更加便捷的方式在測試代碼中使用容器的對象。這個知識點只是為了在測試時更加方便,不使用也沒有關系。
二、Spring整合junit測試
1. 需要引入一個新的jar包
spring-test-4.2.4.RELEASE.jar
2. 使用註解
@RunWith(SpringJUnit4ClassRunner.class) //幫我們創建容器
但是由於Spring配置文件位置和名字任意,所以得指明配置文件位置和名稱。
@ContextConfiguration("classpath:com/wisedu/annotation/applicationContext.xml") //指定創建容器時使用哪個文件 //@ContextConfiguration(locations = "classpath:com/wisedu/annotation/applicationContext.xml")
另外,原來在每個測試方法裏都要手動獲取對象,現在我們可以使用為變量註入值:
@Resource(name = "user") private User u;
編寫測試方法:
@Test public void test3(){ System.out.print(u); }
這樣每個測試方法裏都不需要手動創建容器和手動獲取對象了。
整個代碼如下:
@RunWith(SpringJUnit4ClassRunner.class) //幫我們創建容器 @ContextConfiguration("classpath:com/wisedu/annotation/applicationContext.xml") //指定創建容器時使用哪個文件 //@ContextConfiguration(locations = "classpath:com/wisedu/annotation/applicationContext.xml") public class test { //將名為user的對象註入到u變量中 @Resource(name = "user") private User u; @Test public void test3(){ System.out.print(u); } }
Spring整合junit測試