【发布时间】:2021-10-10 17:38:45
【问题描述】:
我想对我的方法进行单元测试,该方法从最后插入的对象的数据库 id 返回:
public int getLastId() throws SQLException {
String query = "select LAST_INSERT_ID();";
PreparedStatement stmt = connection.prepareStatement(query);
int id = -1;
ResultSet resultSet = stmt.executeQuery();
while (resultSet.next()) {
id = resultSet.getInt("LAST_INSERT_ID()");
}
return id;
}
然后我想像这样进行相同的单元测试:
dataBaseService = mock(DataBaseService.class);
resultSet = mock(ResultSet.class);
@Test
public void getLastIdIsCorrect() throws SQLException {
//given
int expectedId = 1;
int expectedIncorrectId = 101;
//when
when(resultSet.getInt("LAST_INSERT_ID()")).thenReturn(1);
when(dataBaseService.getLastId()).thenCallRealMethod();
int result = dataBaseService.getLastId();
//then
Assert.assertEquals(expectedId, result);
Assert.assertNotEquals(expectedIncorrectId, result);
}
但是我得到空指针异常符合 PreparedStatement stmt = connection.prepareStatement(query);
您能否解释一下,如何正确地进行这样的单元测试?遇到同样问题的方法很少,我还在学习单元测试....
【问题讨论】:
标签: unit-testing mocking mockito resultset