【发布时间】:2014-06-24 21:12:43
【问题描述】:
我目前正在测试一种方法updateIssuesTable()。此方法是私有 void 方法。更糟糕的是,这个方法内部是对getConnection()的调用,它返回一个Connection,并且依赖于几个私有变量,这些私有变量依赖于一个初始化方法,而初始化方法当然依赖于其他东西。
长话短说,这行代码:
Connection conn = getConnection();
我根本不想执行,我只需要一个模拟的连接来继续执行。下面是测试方法:
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);
【问题讨论】:
-
您最好在程序的主类中创建
Connection对象。在您想使用它的每个类的方法()中,call that method of Main Class which would return an instance of the Connection Object! -
这个方法仍然需要建立连接,通过调用像
getConnection()这样的方法。我不太确定您的建议是什么,或者为什么会有所帮助。 -
其实我没看懂你说的
mocking是什么意思?对不起,如果你觉得我在不知情的情况下发表评论感到内疚!但是,我认为您每次可能只需要一个 Connection 对象来连接。再次为这样的错误道歉!
标签: java junit mockito white-box