3 實(shí)裝測(cè)試方法,詳細(xì)見代碼注釋。
*檢索類方法,可以利用assertEquals()方法,拿表的字段進(jìn)行比較。
// findStudent
public void testFindStudent() throws Exception{
//執(zhí)行findStudent方法
StudentOpe studentOpe=new StudentOpe();
Student result = studentOpe.findStudent("0001");
//預(yù)想結(jié)果和實(shí)際結(jié)果的比較
assertEquals("翁仔",result.getName());
assertEquals("m",result.getSex());
assertEquals("1979-12-31",result.getBirthDay());
}
*更新,添加,刪除等方法,可以利用Assertion.assertEquals()方法,拿表的整體來比較。
public void testAddStudent() throws Exception{
//執(zhí)行addStudent方法
StudentOpe studentOpe=new StudentOpe();
//被追加的記錄
Student newStudent = new Student("0088","王耳朵","m","1982-01-01");
//執(zhí)行追加方法
Student result = studentOpe.addStudent(newStudent);
//預(yù)想結(jié)果和實(shí)際結(jié)果的比較
IDatabaseConnection connection=null;
try{
//預(yù)期結(jié)果取得
IDataSet expectedDataSet = new FlatXmlDataSet(new FileInputStream("student_exp.xml"));
ITable expectedTable = expectedDataSet.getTable("student");
//實(shí)際結(jié)果取得
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();
}
}
*如果在整體比較表的時(shí)候,有個(gè)別字段不需要比較,可以用DefaultColumnFilter.excludedColumnsTable()方法,
將指定字段給排除在比較范圍之外。比如上例中不需要比較birthday這個(gè)字段的話,那么可以如下代碼所示進(jìn)行處理:
ITable filteredExpectedTable = DefaultColumnFilter.excludedColumnsTable(expectedTable, new String[]{"birthday"});
ITable filteredActualTable = DefaultColumnFilter.excludedColumnsTable(actualTable,new String[]{"birthday"});
Assertion.assertEquals(filteredExpectedTable, filteredActualTable);
4 在tearDown()方法里邊,把數(shù)據(jù)庫(kù)還原到測(cè)試前狀態(tài)
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){}
}
}