我正在处理一个项目,我们需要创建一些测试用例。我有一个SQL数据库并使用以下查询解析数据:
public Contractor create(String name, String address, String email, String phone, String city, int cvr) throws SQLException{
Contractor contractor = new Contractor(name, address, email, phone, city, cvr);
String sql = String.format("INSERT INTO person (name, address, email, phone, city, category) VALUES ('%s', '%s', '%s', '%s', '%s', 2)", name, address, email, phone, city);
try{
Connection conn = DBConnection.getInstance().getDBcon();
conn.createStatement().executeUpdate(sql);
String sql2 = "SELECT TOP 1 id FROM Person ORDER BY id DESC";
ResultSet rs = conn.createStatement().executeQuery(sql2);
if(rs.next()) {
String sql3 = "INSERT INTO contractor (cvr, person_id) VALUES (2666,"+rs.getInt("id")+")";
conn.createStatement().executeUpdate(sql3);
}else{
throw new SQLException();
}
} catch (SQLException e){
e.printStackTrace();
} finally {
DBConnection.closeConnection();
}
return contractor;
}
JUnits的测试结果如何?
答案 0 :(得分:4)
嗯,必须使用Junit的方法是测试你的类的每个公共方法,并且实验数量可以成功或失败。
然后,每种测试方法都必须:
在您的情况下,检查结果很困难,因为您的方法会在本地管理连接。更糟糕的是:数据会自动提交到连接中,在每次测试时都会在数据库中留下脏记录。
为了避免这种困难,只需稍加前面的重构就可以简化测试开发:
create
,使用包访问版本接收连接,并将所有业务逻辑放在那里。然后,您可以安全地进行测试:
MyClass
,请在同一个包中创建MyClassTest
(通常位于不同的源路径中,例如Maven项目中的src\test\java
)。createSinglePerson()
,它使用一组任意参数和一个连接(不是自动提交)调用create
。之后,您必须检查 Person 表中最初有一条记录,其中包含一组特定值,并且 Contractor 表中还有一条记录某些价值观。要比较每个值,您必须使用Asserts.assertEquals(expected, real)
。最后(在finally子句中),回滚到连接并关闭它。您可以根据需要多次运行测试,因为它知道它不会改变数据库状态。
(注意:从不使用参数cvr
。也许你故意这样做,我不知道。)
public class MyClassTest
{
@Test
public void createSinglePerson()
{
MyClass myClass=new MyClass();
try(Connection connection=...)
{
try(Statement stCheck=connection.createStatement())
{
connection.setAutoCommit(false);
// Initial cleanup:
stCheck.executeUpdate("DELETE FROM person");
stCheck.executeUpdate("DELETE FROM contractor");
// Setting input parameters:
String name="a";
String address="b";
String email="c@d.e";
String phone="001";
String city="f";
int cvr=11;
// Do the call:
Contractor contractor=myClass.create(name, address, email, phone, city, cvr);
// Javabean Checks: Check the javabean contains the expected values:
assertEquals(name, contractor.getName());
assertEquals(address, contractor.getAddress());
...
// Database Checks:
int personId;
// Check the Person table contains one row with the expected values:
try(ResultSet rs=stCheck.executeQuery("SELECT * FROM person"))
{
assertTrue(rs.next());
personId=rs.getInt("id");
asssertEquals(name, rs.getString("name"));
asssertEquals(address, rs.getString("address"));
...
assertFalse(rs.next());
}
// Check the Contractor table contains one row with the expected values:
try(ResultSet rs=stCheck.executeQuery("SELECT * FROM contractor WHERE person_id="+personId))
{
assertTrue(rs.next());
asssertEquals(2666, rs.getInt("cvr"));
...
assertFalse(rs.next());
}
}
finally
{
// Undo the testing operations:
connection.rollback();
}
}
catch (SQLException e)
{
fail(e.toString());
}
}
}