【问题标题】:JUnit test is still passing even though sql query should return no records即使 sql 查询不应该返回任何记录,JUnit 测试仍然通过
【发布时间】:2018-10-17 11:23:10
【问题描述】:

我正在编写查询 SQL Server 数据库的黄瓜测试。

下面的查询应该失败,因为表中不存在记录。但是,测试通过了。

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!"); 
} 

【问题讨论】:

  • 您的查询结果如何?
  • @YitianZhang 嗨,我已经添加了上面应该失败的代码。所以这个方法应该在上面失败。您可以看到我添加的 sys.out,但以下详细信息是唯一记录到控制台的详细信息:正在连接数据库...已成功连接数据库...再见!
  • 如果表中不存在记录,则结果集将为空,这意味着永远不会执行assertEquals(60115, id);
  • @ThomasKläger 嗨,好的,谢谢。如果结果集为空,我需要对代码进行哪些更改以使其失败?
  • 如果没有发现它应该失败,那么你可以用一个简单的检查替换你的while (rs.next()) { ... }循环:if (!rs.next()) { fail("No data found"); }

标签: java sql junit cucumber junit4


【解决方案1】:

您在以下行中有NullPointerException

int id  = rs.getInt("goald_client_id"); 

它进入异常块,只需在所有异常块中添加以下语句

assertEquals(true, false);

【讨论】:

  • 我已将它添加到所有的 catch 语句中,但测试仍然通过
【解决方案2】:

您的 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    相关资源
    最近更新 更多