3 实装测试方法,详细见代码注释。
*检索类方法,可以利用assertEquals()方法,拿表的字段进行比较。
// findStudent
public void testFindStudent() throws Exception{
//执行findStudent方法
StudentOpe studentOpe=new StudentOpe();
Student result = studentOpe.findStudent("0001");
//预想结果和实际结果的比较
assertEquals("翁仔",result.getName());
assertEquals("m",result.getSex());
assertEquals("1979-12-31",result.getBirthDay());
}
*更新,添加,删除等方法,可以利用Assertion.assertEquals()方法,拿表的整体来比较。
public void testAddStudent() throws Exception{
//执行addStudent方法
StudentOpe studentOpe=new StudentOpe();
//被追加的记录
Student newStudent = new Student("0088","王耳朵","m","1982-01-01");
//执行追加方法
Student result = studentOpe.addStudent(newStudent);
//预想结果和实际结果的比较
IDatabaseConnection connection=null;
try{
//预期结果取得
IDataSet expectedDataSet = new FlatXmlDataSet(new FileInputStream("student_exp.xml"));
ITable expectedTable = expectedDataSet.getTable("student");
//实际结果取得
Connection conn=getConnection();
connection =new DatabaseConnection(conn);
IDataSet databaseDataSet = connection.createDataSet();
ITable actualTable = databaseDataSet.getTable("student");
//比较
Assertion.assertEquals(expectedTable, actualTable);
}finally{
if(connection!=null) connection.close();
}
}
*如果在整体比较表的时候,有个别字段不需要比较,可以用DefaultColumnFilter.excludedColumnsTable()方法,
将指定字段给排除在比较范围之外。比如上例中不需要比较birthday这个字段的话,那么可以如下代码所示进行处理:
ITable filteredExpectedTable = DefaultColumnFilter.excludedColumnsTable(expectedTable, new String[]{"birthday"});
ITable filteredActualTable = DefaultColumnFilter.excludedColumnsTable(actualTable,new String[]{"birthday"});
Assertion.assertEquals(filteredExpectedTable, filteredActualTable);
4 在tearDown()方法里边,把数据库还原到测试前状态
protected void tearDown() throws Exception{
IDatabaseConnection connection =null;
try{
super.tearDown();
Connection conn=getConnection();
connection =new DatabaseConnection(conn);
IDataSet dataSet = new FlatXmlDataSet(file);
DatabaseOperation.CLEAN_INSERT.execute(connection,dataSet);
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(connection!=null) connection.close();
}catch(SQLException e){}
}
}