2011-11-26 88 views
0

我有一個Customer類,它連接到db並將數據保存到mysql。我使用tomcat7和mysql。我想測試這個類。我有這種方法:與db連接的Java測試類

public CustomerData findById(int customerId) throws SQLException { 
    Connection conn = null; 
    PreparedStatement stmt = null; 
    CustomerData customer = null; 

    try { 
     String sql = "SELECT id, status, username, email, age, country, city, is_hidden FROM " 
       + TABLE + " WHERE id = ?"; 

     conn = DBManager.getConnection(); 
     stmt = conn.prepareStatement(sql); 

     stmt.setInt(1, customerId); 

     ResultSet rs = stmt.executeQuery(); 

     if (rs.next()) { 
      customer = new CustomerData(rs.getInt(1), rs.getInt(2), 
        rs.getString(3), null, rs.getString(4), rs.getInt(5), 
        String.valueOf(rs.getInt(6)), String.valueOf(rs 
          .getInt(7)), 0, rs.getInt(8)); 
     } 

     return customer; 
    } finally { 
     closeConnection(conn, stmt); 
    } 
} 

我該如何測試它?

+0

你想測試什麼?那裏幾乎沒有任何邏輯。 – Thilo

+0

我想測試sql語法並返回數據 –

+0

如果你想測試連接,你應該測試DBManager。如果你想測試CustomerData.findById,並且你想編寫一個單元測試,你應該使用模擬對象。 – erimerturk

回答

3

你可以像你想要的那樣測試它,我建議你創建一個單獨的數據庫,然後分離生產和測試數據。

你應該看看從dallaway,這絕對輝煌的文章。

1

你應該有一個數據庫測試與預填充數據。您可以用固定的customerId anche調用findById對照一些常量檢查結果。 假設你對測試數據庫客戶名稱爲「測試」 registrationDate「10/10/2010」和Id 1 你可能喜歡的東西最終

CustomerData customer = yourclass.findById(1); 
Assert.assertNotNull(customer); 
Assert.assertEquals(customer.getId(),1); 
Assert.assertEquals(customer.getName(),"Test"); 
Assert.assertEquals(customer.getRegistrationDate(),"10/10/2010"); 

這裏斷言類是一個vailable從Junit的ØTestNG的或你測試框架。