在作測試的時候咱們用到Junit Case,當咱們的項目中使用了Sring的時候,咱們應該怎麼使用spring容器去管理個人測試用例呢?如今咱們用一個簡單的例子來展現這個過程。java
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.jarspring
2新建一個HelloWord類,包含一個公有的sayHelloWord方法,咱們的測試主要就是測試這個類的方法:
package Domain;express
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
app
4 建立junit case 進行測試
package Test;dom
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測試例子大致過程。測試