天天看點

使用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,你就明白了什麼回事。

本文轉自yunlielai51CTO部落格,原文連結:http://blog.51cto.com/4925054/1062624,如需轉載請自行聯系原作者