我目前正在测试一种方法updateIssuesTable()
。此方法是私有 void 方法。更糟糕的是,这个方法内部是对 的调用getConnection()
,它返回 a Connection
,并且依赖于几个私有变量,这些私有变量依赖于一个初始化方法,而这个初始化方法当然依赖于其他东西。
长话短说,这行代码:
Connection conn = getConnection();
我根本不想执行,我只需要一个模拟的 Connection 来继续执行。下面是测试方法:
public void testUpdateIssuesTable() throws Exception {
PatchWriterTask task = new PatchWriterTask();
String sql = "update val_issues set PATCH_CREATION_INFO = ? where VAL_ISSUE_ID = ?";
when(task1.getConnection()).thenReturn(conn);
when(conn.prepareStatement(sql)).thenReturn(updateStatement);
Whitebox.invokeMethod(task, "updateIssuesTable");
}
我正在测试的方法如下:
private void updateIssuesTable() throws SQLException {
PreparedStatement createStatement = null;
String sql = "update val_issues set PATCH_CREATION_INFO = ? where VAL_ISSUE_ID = ?";
Connection conn = getConnection();
createStatement = conn.prepareStatement(sql);
...
}
编辑:我在我的测试类中创建了一个模拟连接:
private Connection conn = mock(Connection.class);