`

写了半天的DAOTest基类。

    博客分类:
  • Java
阅读更多
package test.javayuan.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;

import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.junit.After;
import org.junit.Before;

import test.javayuan.exception.TestRuntimeException;

/**
 * @(#)DAOTest.java 2008-12-4 下午12:46:42
 * 
 * @author Qiu Maoyuan
 * DAO Test
 */
public abstract class DAOTest extends BaseTest{
	
	private File backupFile;
	private String backupFileName;
	private String preparedFileName;
	private String[] backupTableNames;
	
	private String jdbcDriverName = "com.mysql.jdbc.Driver";
	private String url = "jdbc:mysql://127.0.0.1:3306/yuan";
	private String username = "root";
	private String password = "";

	protected final IDatabaseConnection databaseConnection = getDatabaseConnection(url, username, password);
	
	protected void setBackupFileName(String backupFileName) {
		this.backupFileName = backupFileName;
	}

	protected void setPreparedFileName(String preparedFileName) {
		this.preparedFileName = preparedFileName;
	}

	protected void setBackupTableNames(String[] backupTableNames) {
		this.backupTableNames = backupTableNames;
	}
	
	/**
	 * SetUp
	 */
	@Before
	public void setUp(){
		onSetUp();
		backupData();
		prepareData();
	}
	
	/**
	 * TearDown
	 */
	@After
	public void tearDown(){
		onTearDown();
		restoreData();
		deleteBackupFile();
		cleanResource();
	}
	
	/**
	 * OnSetUp
	 */
	protected abstract void onSetUp();
	
	/**
	 * OnTearDown
	 */
	protected abstract void onTearDown();
	
	/**
	 * 获取指定文件名的文件:该文件应该是个DBUnit专用的数据文件,应该被放在TestCase类文件所在目录下。<br/>
	 * 如果数据文件不存在,或者存放位置不对,则抛出FileNotFoundException。
	 * @param fileName 文件名
	 * @return 指定文件名的文件
	 * @throws FileNotFoundException 如果数据文件不存在,或者存放位置不对,则抛出FileNotFoundException。
	 */
	protected File getDataFile(String fileName) throws FileNotFoundException{
		String absoluteFilePath = generateAbsolutePath(fileName);
		File file = new File(absoluteFilePath);
		if(!file.exists())
			throw new FileNotFoundException("文件名:" + absoluteFilePath);
		
		return file;
	}
	
	/**
	 * 获取DBUnit数据库连接
	 * @param url 数据库URL
	 * @param user 数据库用户名
	 * @param password 数据库登录密码
	 * @return DBUnit数据库连接
	 */
	private IDatabaseConnection getDatabaseConnection(String url, String user, String password){
		Connection connection; 
		IDatabaseConnection databaseConnection = null;
		try{
			Class.forName(jdbcDriverName);
			connection = DriverManager.getConnection(url, user, password);
			databaseConnection = new DatabaseConnection(connection);
		}catch(Exception ex){
			throw new TestRuntimeException(ex);
		}
		return databaseConnection;
	}
	
	/**
	 * 备份数据库数据
	 */
	private void backupData(){
		if(backupTableNames == null)
			throw new TestRuntimeException("未指定要备份的数据库表:backupTableNames");
		QueryDataSet backupDataSet = new QueryDataSet(databaseConnection);
		FileOutputStream fos = null;
		
		for(String tableName : backupTableNames)
			backupDataSet.addTable(tableName);
		
		try {
			backupFile = createBackupFile();
			fos =  new FileOutputStream(backupFile);
			FlatXmlDataSet.write(backupDataSet, fos);
		} catch (Exception ex){
			throw new TestRuntimeException(ex);
		} finally{
			if(fos != null)
				try {
					fos.close();
				} catch (IOException ex) {
					throw new TestRuntimeException(ex);
				}
		}
	}
	
	/**
	 * 导入“准备数据”
	 */
	private void prepareData(){
		if(preparedFileName == null)
			throw new TestRuntimeException("未指定“准备数据”的文件名:preparedFileName");
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(getDataFile(preparedFileName));
			IDataSet dataSet = new FlatXmlDataSet(fis);
			DatabaseOperation.CLEAN_INSERT.execute(databaseConnection, dataSet);
		} catch (Exception ex) {
			throw new TestRuntimeException(ex);
		} finally{
			if(fis != null)
				try {
					fis.close();
				} catch (IOException ex) {
					throw new TestRuntimeException(ex);
				}
		}
	}

	/**
	 * 还原备份数据
	 */
	private void restoreData(){
		try {
			IDataSet backupData = new FlatXmlDataSet(backupFile);
			DatabaseOperation.CLEAN_INSERT.execute(databaseConnection, backupData);
		} catch (Exception ex) {
			throw new TestRuntimeException(ex);
		}
	}
	
	/**
	 * 删除备份文件
	 */
	private void deleteBackupFile(){
		boolean deleted = backupFile.delete();
		if(!deleted)
			throw new TestRuntimeException("备份文件“"+ backupFile.getAbsolutePath() + "”未正确删除。");
	}
	
	/**
	 * 清理资源
	 */
	private void cleanResource(){
		try {
			databaseConnection.close();
		} catch (Exception ex) {
			throw new TestRuntimeException(ex);
		}
	}
	
	/**
	 * 生成指定文件名的绝对路径<br/>
	 * 生成格式:当前类文件所在绝对路径 + fileName
	 * @param fileName 文件名
	 * @return 指定文件名的绝对路径
	 */
	private String generateAbsolutePath(String fileName){
		return getSystemPath() + getPackagePath() + "/" + fileName;
	}
	
	/**
	 * 创建备份文件<br/>
	 * 如果指定了备份文件的文件名,则创建一个指定文件名的文件;否则,创建一个临时备份文件。
	 * @return 备份文件
	 */
	private File createBackupFile(){

		if(backupFileName != null)
			return new File(generateAbsolutePath(backupFileName));
		else
			try {
				return File.createTempFile("DATABASE_BACKUP", ".xml");
			} catch (IOException ex) {
				throw new TestRuntimeException(ex);
			}
	}
	
	/**
	 * 获取当前类所在包对应的文件路径
	 * @return 当前类所在包对应的文件路径
	 */
	private String getPackagePath(){		
		return getClass().getPackage().getName().replace('.', '/');
	}
	
	/**
	 * 获取当前系统根目录
	 * @return 当前系统根目录
	 */
	private String getSystemPath(){
		return getClass().getClassLoader().getResource("").getFile();
	}
}


BaseTest就这么点内容,主要是加载SpringContext啦:
package test.javayuan.base;

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;

/**
 * @(#)BaseTest.java 2008-11-25 下午07:44:42
 * 
 * @author Qiu Maoyuan
 * Base Test
 */
@ContextConfiguration(locations={"classpath:spring-config-4test.xml"})
public abstract class BaseTest extends AbstractJUnit4SpringContextTests{

}

实现了个子类,试了试,运行正常:
package test.javayuan.blog.dao;

import java.io.FileInputStream;
import java.util.Date;

import net.javayuan.blog.dao.BlogDAO;
import net.javayuan.blog.entity.Blog;

import org.dbunit.Assertion;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.filter.DefaultColumnFilter;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import test.javayuan.base.DAOTest;

/**
 * @(#)BlogDAOTest.java 2008-11-25 下午01:49:12
 * 
 * @author Qiu Maoyuan
 * Blog DAO Test
 */
public class BlogDAOTest extends DAOTest {
	
	@Autowired
	private BlogDAO blogDAO;
	
	public void setBlogDAO(BlogDAO blogDAO){
		this.blogDAO = blogDAO;
	}

	@Override
	protected void onSetUp() {
		this.setBackupFileName("BLOG_BAK.xml");
		this.setPreparedFileName("BLOG_PRE.xml");
		this.setBackupTableNames(new String[]{"t_blog"});
	}

	@Override
	protected void onTearDown() {
		
	}
	
	/**
	 * 测试保存BLOG
	 */
	@Test
	public void testSaveBlog() throws Exception{
		Blog blog = new Blog("title2", "content2");
		blog.setCreatedTime(new Date());
		blogDAO.save(blog);
		
		IDataSet expectedDataSet = new  FlatXmlDataSet(new FileInputStream(getDataFile("BLOG_EXP.xml")));
		ITable expectedTable = expectedDataSet.getTable("t_blog");
		IDataSet databaseDataSet = databaseConnection.createDataSet();
		ITable filteredTable = DefaultColumnFilter.includedColumnsTable(databaseDataSet.getTable("t_blog"),
				expectedTable.getTableMetaData().getColumns());
		
		Assertion.assertEquals(expectedTable, filteredTable);
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics