2013-10-01 96 views
0
public static void sql() { 
    String url = "jdbc:msql://carthage.imaginary.com/ora"; 
    Connection con = null; 

    try { 
     String driver = "com.imaginary.sql.msql.MsqlDriver"; 

     Class.forName(driver).newInstance(); 
    } catch (Exception e) { 
     System.out.println("Failed to load mSQL driver."); 
     return; 
    } 
    try { 
     con = DriverManager.getConnection(url, "borg", ""); 
     Statement select = con.createStatement(); 
     ResultSet result = select 
      .executeQuery("SELECT test_id, test_val FROM test"); 

     System.out.println("Got results:"); 
     while (result.next()) { // process results one row at a time 
     int key = result.getInt(1); 
     String val = result.getString(2); 

     System.out.println("key = " + key); 
     System.out.println("val = " + val); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 
     if (con != null) { 
     try { 
      con.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     } 
    } 
    } 
} 

我必須爲Junit對一堆SQL方法做一些測試,我不知道我可以用這些代碼做些什麼。我知道如何使用斷言和期望的異常,但這些在這裏是沒用的。你可以用這些代碼做什麼樣的JUnit測試?

+1

你可以將這些重構成更小的工作單元嗎?由此,我的意思是不同的方法(一個連接,一個獲得結果,一個打印結果等)。如果可以的話,那麼你當然可以編寫測試來測試每個單獨的功能。 –

回答

0

首先我會將代碼重新分成兩部分。

1 .create connection 

2. Get connection object and do operation. 

你在你的代碼中組合了兩者。

我會做如下測試用例

首先編寫一個junit類來測試連接。

Class GenericDAO 
public static Connection getConnection(){ 

    do your sql steps and return connection object 

} 

和您的測試類應該是

public class TestConnection { 

    public void testConnection(){ 
    Connection con = GenericDAO.getConnection(); 

    assert here for not null 
    Assert.assertForNotNull(con); 
    } 

add test cases for other boundary condition 

} 

以後你可以編寫單獨的測試用例其它表的SQL查詢

測試表

public class TestDAO 
     //either you pass conection object or inherit from parent class 
     public String retrieveResults(){ 
     do opertaion here 

    } 
    } 

,你將有獨立的junit爲此

class TestDAOTest{ 

    public void testForResults(){ 

    String str = testDAO.retreiveResults(); 

    do assertrtion as per your wise 

    assert for null, or specific string, negative test cases etc. Note , each can be a separate test cases, by this we are covering boundary conditions 

    } 

} 

最後,您可以測試合併到測試套件,並運行起來

http://www.tutorialspoint.com/junit/junit_suite_test.htm

0

首先,我建議你寫一些測試用例。然後你實現所需要的方法(重構這些代碼到方法中)。

0

你的方法不返回任何東西,所以我覺得這是你的方法只是玩弄? 通常,DAO中的方法將返回,插入,更新或刪除值。這些是你可以測試的東西。

相關問題