即使 sql 查询应该 return 没有记录,JUnit 测试仍然通过
JUnit test is still passing even though sql query should return no records
我正在编写查询 SQL 服务器数据库的黄瓜测试。
下面的查询应该会失败,因为 table 中不存在该记录。但是,测试通过了。
try {
Class.forName(JDBC_DRIVER);
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Connected database successfully...");
stmt = conn.createStatement();
String sql = "SELECT id FROM tclientlink WHERE id = '0000060115123'";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
int id = rs.getInt("goald_client_id");
System.out.print("ID IS HERE: " + id);
assertEquals(60115, id);
}
rs.close();
} catch(SQLException se) {
se.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt!=null) stmt.close();
} catch(SQLException se2) {
}
try {
if(conn!=null) conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
您在以下行中有 NullPointerException
:
int id = rs.getInt("goald_client_id");
然后进入异常块,只需要在所有异常块中添加如下语句
assertEquals(true, false);
您的 while 循环没有执行,因为结果集中没有记录,默认情况下测试用例已通过,
请进行以下更改
while(rs.next()) {
int id = rs.getInt("goald_client_id");
System.out.print("ID IS HERE: " + id);
assertEquals(60115, id);
}
将上面的代码更改为
int noOfRecords = 0;
while(rs.next()) {
int id = rs.getInt("goald_client_id");
System.out.print("ID IS HERE: " + id);
assertEquals(60115, id);
noOfRecords ++;
}
if( noOfRecords == 0 ) {
assertEquals(true, false);
}
我正在编写查询 SQL 服务器数据库的黄瓜测试。
下面的查询应该会失败,因为 table 中不存在该记录。但是,测试通过了。
try {
Class.forName(JDBC_DRIVER);
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Connected database successfully...");
stmt = conn.createStatement();
String sql = "SELECT id FROM tclientlink WHERE id = '0000060115123'";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
int id = rs.getInt("goald_client_id");
System.out.print("ID IS HERE: " + id);
assertEquals(60115, id);
}
rs.close();
} catch(SQLException se) {
se.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt!=null) stmt.close();
} catch(SQLException se2) {
}
try {
if(conn!=null) conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
您在以下行中有 NullPointerException
:
int id = rs.getInt("goald_client_id");
然后进入异常块,只需要在所有异常块中添加如下语句
assertEquals(true, false);
您的 while 循环没有执行,因为结果集中没有记录,默认情况下测试用例已通过, 请进行以下更改
while(rs.next()) {
int id = rs.getInt("goald_client_id");
System.out.print("ID IS HERE: " + id);
assertEquals(60115, id);
}
将上面的代码更改为
int noOfRecords = 0;
while(rs.next()) {
int id = rs.getInt("goald_client_id");
System.out.print("ID IS HERE: " + id);
assertEquals(60115, id);
noOfRecords ++;
}
if( noOfRecords == 0 ) {
assertEquals(true, false);
}