DbUnit使用入门

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());
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值