Spring TestContext

使用Spring TestContext 測試框架,完美測試基於Spring的應用程序       

 

至於Spring TestContext是個什麼東西,各位只要google下就可以知道了。Spring TestContext爲什麼好?我只說一點,只使用Junit進行單元測試時,數據庫現場容易遭受破壞,而Spring TestContext剛可以很好的做到單元測試後恢復現場,使用的是事務回滾機制。

經過本人的實際使用,現在簡單說明一下Spring TestContext的使用:

1,加jar包:

                如果你使用的是spring2.5.6,請把/spring-framework-2.5.6/dist/modules/spring-test.jar   copy到你的web項目的lib下。

2,寫測試類,要從AbstractTransactionalJUnit4SpringContextTests繼承。

package com.gxing.registration.service.impl;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;

import com.gxing.registration.model.User;
import com.gxing.registration.service.UserManager;

@ContextConfiguration
public class UserManagerImplTest extends AbstractTransactionalJUnit4SpringContextTests{

    @Autowired
    private UserManager userManager;
   
    @Test
    public void testAdd() {
        //ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        //UserManager um = (UserManager) ctx.getBean("userManager");
       
        User u = new User();
        u.setUsername("testService");
        u.setPassword("testPassword");
        userManager.add(u);
    }

}

3,加上如測試代碼中的Annotion,不明白就google,我不作解釋,把這個權利留着給google老師。

3,編寫UserManagerImplTest-context.xml文件,與上面的文件放到同一個包中

<?xml version="1.0" encoding="UTF-8" ?>
< beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">


< import resource="classpath:/beans.xml"/>

< /beans>

4,把Juint4.4以上的jar包copy進web-info下的lib中。一定要注意是4.4以上的版本才支持。

5,Run as Juint Test,看看,測試通過了,但是我們的數據庫裏沒有增加一個記錄,看看控制檯的Logger,你就明白了什麼回事。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章