2011-11-26 104 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的或你测试框架。