在做測試的時候我們用到Junit Case,當我們的項目中使用了Sring的時候,我們應該怎么使用spring容器去管理我的測試用例呢?現在我們用一個簡單的例子來展示這個過程。
-
1 首先我們新建一個普通的java項目,引入要使用的幾個jar包。
spring測試類的要用的jar包:
1.spring-test-3.2.4.RELEASE.jar
spring的核心jar包:
1.spring-beans-3.2.4.RELEASE.jar
2.spring-context-3.2.4.RELEASE.jar
3.spring-core-3.2.4.RELEASE.jar
4.spring-expression-3.2.4.RELEASE.jar
spring的依賴jar包:
1.commons-logging-1.1.1.jar -
2新建一個HelloWord類,包含一個公有的sayHelloWord方法,我們的測試主要就是測試這個類的方法:
package Domain;public class HelloWord { /** * * @Description: 方法 (這里用一句話描述這個類的作用) * @author Jack * @date 2016年6月15日 下午3:27:43 */ public void sayHelloWord(){ System.out.println("Hello Word ....."); } } -
3 引入spring配置文件applicationContext.xml,配置bean

-
4 創建junit case 進行測試
package Test;import static org.junit.Assert.*; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import Domain.HelloWord; public class HelloWordTest { @Test /** * * @Description: 普通的單元測試(這里用一句話描述這個類的作用) * @author Jack * @date 2016年6月15日 下午4:33:53 */ public void test() { HelloWord domain=new HelloWord(); domain.sayHelloWord(); } @Test /** * * @Description: 加載spring容器獲得bean進行測試 (這里用一句話描述這個類的作用) * @author Jack * @date 2016年6月15日 下午4:34:19 */ public void testSpring(){ ApplicationContext ctx=new ClassPathXmlApplicationContext("resource/applicationContext.xml"); HelloWord word=(HelloWord) ctx.getBean("helloWord"); word.sayHelloWord(); } }
上面測試用例中,一個是常規的方式(通過主動創建實例對象方式)的測試,一個是通過加載spring容器的方式獲得容器提供的實例進行測試。
然而上述所說的方式卻存在兩個問題:
1.每一個測試都要重新啟動spring容器
2.測試的代碼在管理spring容器(與我們的目的相反)
為了達到目的我們就要用到spring-test-3.2.4.RELEASE.jar這個jar包里提供的方法去實現。測試的代碼如下:
package Test;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import Domain.HelloWord;
//告訴spring容器運行在虛擬機中
@RunWith(SpringJUnit4ClassRunner.class)
//配置文件的位置
//若當前配置文件名=當前測試類名-context.xml 就可以在當前目錄中查找@ContextConfiguration()
@ContextConfiguration("classpath:resource/applicationContext.xml")
public class SpringHelloWordTest {
@Autowired
//自動裝配
private ApplicationContext cxf;
@Test
public void test() {
HelloWord word=(HelloWord) cxf.getBean("helloWord");
word.sayHelloWord();
}
}
上述就是整個簡單的Spring測試例子大體過程。
