使用DBUnit做单元测试
作者:网络转载 发布时间:[ 2013/11/22 16:01:07 ] 推荐标签:
下面这个MyTest类,是用于单元测试的类:
|
package com.ubs.cre.tools.datatool.ipl;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import junit.framework.Assert;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.ReplacementDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.junit.Test;
import com.ubs.cre.BasedTestCase;
public class MyTest extends BasedTestCase {
@Test
public void testSend() throws IOException, SQLException {
Connection conn = null;
Boolean result = Boolean.FALSE;
IDatabaseConnection iconn = null;
try {
//Get DBUnit conneciton
iconn = getIDatabaseConnection();
//Get database connection
conn = iconn.getConnection();
//Set auto commit false
conn.setAutoCommit(false);
//prepare data
prepareData(iconn);
//use reflect to set the commit field to false
Class<UpdateTest> clazz = UpdateTest.class;
Field commitField = clazz.getDeclaredField("commit");
commitField.setAccessible(true);
commitField.setBoolean(clazz, false);
//call the method updateFiled
Method method = clazz.getDeclaredMethod("updateFiled", java.sql.Connection.class);
method.setAccessible(true);
//Before call the method, the clazz must be get an new install, because the called method "updateFiled" is not static.<br>
//If the called method is static, it will not need newInstance.
method.invoke(clazz.newInstance(), conn);
// get result data set by result xml file
ReplacementDataSet dataload_result = createDataSet(Thread.currentThread().getContextClassLoader().getResourceAsStream("MyTest_Result.xml"));
// compare the data which get from database and the expected result file
assertDataSet("YouTableName_1", "select filed_1,filed_2,filed_3 from YouTableName_1 order by filed_1", dataload_result, iconn);
} catch (Exception e) {
e.printStackTrace();
Assert.assertTrue(result);
} finally {
if (conn != null) {
conn.rollback();
conn.close();
}
}
}
protected void prepareData(IDatabaseConnection iconn) throws Exception {
//Remove the data from table YouTableName_1
execSql(iconn, "delete from YouTableName_1");
//INSERT TEST DATA
ReplacementDataSet createDataSet = createDataSet(Thread.currentThread().getContextClassLoader().getResourceAsStream("MyTest.xml"));
DatabaseOperation.INSERT.execute(iconn, createDataSet);
}
}
|
好了,示例完了,非常的简单,也非常的清晰,不过美中不足是和DBUnit的代码耦合度太高了,这过对于我们使用习惯了Spring的人来说,看起来是非常别扭的,后面我会写另外一个与Spring集成的、完全非侵入式的测试实现,等着吧。
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系SPASVO小编(021-61079698-8054),我们将立即处理,马上删除。
相关推荐
iOS单元测试mocha、chai、sinon和istanbul实现百分之百的单元测试覆盖率关于单元测试的总结及思考编写更好的Java单元测试的7个技巧Android单元测试框架Robolectric3.0介绍(一)使用Kiwi单元测试总结单元测试如此重要,为什么你不知道Python单元测试??使用装饰器实现测试跳过和预期故障对Controller的单元测试写好单元测试的10个技巧单元测试的重要性Angular单元测试系列??Component、Directive、Pipe 以及ServiceAndroid单元测试的整理提升单元测试体验的利器--Mockito使用总结iOS UnitTest单元测试Vue的单元测试探索(二)

sales@spasvo.com