现在的位置: 首页 > 综合 > 正文

DbUnit使用入门

2012年10月11日 ⁄ 综合 ⁄ 共 2459字 ⁄ 字号 评论关闭

DbUnit 是在JUnit的基础上扩展而成的Java单元测试框架。

如果你的业务逻辑涉及到了对数据库中记录的增、删、改、查操作,而你又不想每次都手动到数据库里查询,来验证你的业务逻辑,那么DbUnit可以帮助你。实际上,如果你的单元测试中只有少量业务逻辑对数据库进行了操作,那么,DbUnit在单元测试中的优势还体现不出来,但是,如果你的单元测试用例中有大量的DAO操作,那么全凭手动执行数据库查询,讲造成工作效率降低,而且可能会遗漏功能点。而且,在回归测试中,验证DAO操作的工作不能重用。

现在就让我们开始认识DbUnit吧!首先介绍org.dbunit.DatabaseTestCase.java类,源码如下:

package org.dbunit;

import junit.framework.TestCase;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.operation.DatabaseOperation;

/** */
public abstract class DatabaseTestCase extends TestCase
{
    
public DatabaseTestCase()
    
{
    }


    
public DatabaseTestCase(String name)
    
{
        
super(name);
    }


    
/**
     * Returns the test database connection.
     
*/

    
protected abstract IDatabaseConnection getConnection() throws Exception;

    
/**
     * Returns the test dataset.
     
*/

    
protected abstract IDataSet getDataSet() throws Exception;

    
/**
     * Close the specified connection. Ovverride this method of you want to
     * keep your connection alive between tests.
     
*/

    
protected void closeConnection(IDatabaseConnection connection) throws Exception
    
{
        connection.close();
    }


    
/**
     * Returns the database operation executed in test setup.
     
*/

    
protected DatabaseOperation getSetUpOperation() throws Exception
    
{
        
return DatabaseOperation.CLEAN_INSERT;
    }


    
/**
     * Returns the database operation executed in test cleanup.
     
*/

    
protected DatabaseOperation getTearDownOperation() throws Exception
    
{
        
return DatabaseOperation.NONE;
    }


    
private void executeOperation(DatabaseOperation operation) throws Exception
    
{
        
if (operation != DatabaseOperation.NONE)
        
{
            IDatabaseConnection connection 
= getConnection();
            
try
            
{
                operation.execute(connection, getDataSet());
            }

            
finally
            
{
                closeConnection(connection);
            }

        }

    }



    
////////////////////////////////////////////////////////////////////////////
    
// TestCase class

    
protected void setUp() throws Exception
    
{
        
super.setUp();

        executeOperation(getSetUpOperation());
    }


    
protected void tearDown() throws Exception
    
{
        
super.tearDown();

        executeOperation(getTearDownOperation());
    }

}


抱歉!评论已关闭.