我试图测试使用DateFormat(SimpleDateFormat)的DAO函数。当我尝试运行测试即时获取:
java.lang.NullPointerException
at java.util.Calendar.setTime(Calendar.java:1770)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:943)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:936)
at java.text.DateFormat.format(DateFormat.java:345)
这指向:election.setStartDate(df.format(rs.getDate(“startDate”)));在DAO
这是测试代码:
@RunWith(MockitoJUnitRunner.class)
public class AdminDaoImplTest {
@Mock
Connection mockConn;
@Mock
PreparedStatement mockPreparedStmnt;
@Mock
ResultSet mockResultSet;
@Mock
DateFormat formatter;
@InjectMocks
private AdminDao adminDao = new AdminDaoImpl();
@Mock
private SQLConnection mockSqlConnection;
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void init() throws SQLException {
when(mockSqlConnection.getConnection()).thenReturn(mockConn);
when(mockConn.prepareStatement(anyString())).thenReturn(mockPreparedStmnt);
when(mockPreparedStmnt.executeQuery()).thenReturn(mockResultSet);
when(mockResultSet.next()).thenReturn(Boolean.TRUE, Boolean.FALSE);
when(formatter.format(any())).thenReturn("'2018-11-12 00:00'");
}
@After
public void tearDown() {
}
@Test
public void testGetElectionsNoExceptions() throws SQLException {
ElectionListResponse electionListResponse = new ElectionListResponse();
adminDao.getElections('>' );
//verify and assert
verify(mockConn, times(1)).prepareStatement(anyString());
verify(mockPreparedStmnt, times(1)).executeQuery();
verify(mockResultSet, times(1)).next();
verify(mockResultSet, times(1)).getInt("id");
verify(mockResultSet, times(1)).getString("name");
verify(mockResultSet, times(1)).getDate("startDate");
verify(mockResultSet, times(1)).getDate("endDate");
}
}
这是DAO中的功能:
@Override
public ElectionListResponse getElections(char selector) {
ElectionListResponse electionListResponse = new ElectionListResponse();
String query = NamedQueries.GET_ELECTIONS_BEGIN + selector + NamedQueries.GET_ELECTIONS_END;
try {
con = sqlConnection.getConnection();
stmt = con.prepareStatement(query);
rs = stmt.executeQuery();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
while (rs.next()) {
Election election = new Election();
election.setElectionID(rs.getInt("id"));
election.setElectionName(rs.getString("name"));
election.setStartDate(df.format(rs.getDate("startDate")));
election.setEndDate(df.format(rs.getDate("endDate")));
electionListResponse.addElection(election);
}
return electionListResponse;
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, "Cant get elections. ", e);
} finally {
closeConnection();
}
return null;
}
我已经尝试了一些我在网上找到的例子,但我仍然得到同样的错误。我也读过DateFormat是一个最终函数,不能被模拟。有一些解决方法,但对我不起作用。我不确定我是否正确实施了这些解决方法。
能否请您提供修复此NullPointer的代码?提前致谢!
首先,我没有看到任何模拟rs.getDate()的东西,所以它将返回null。这可能会导致SimpleDateFormat
的模拟和真实实例出现问题。你可以这样解决:
// (I am using the deprecated constructor for simplicity)
java.sql.Date startDate = new java.sql.Date(2018, 6, 5);
Mockito.when(mockResultSet.getDate("startDate")).thenReturn(startDate);
结合when(formatter.format(any())).thenReturn("'2018-11-12 00:00'")
可能会让你超越异常。但是,看起来,就像你在SimpleDateFormat
中创建一个真正的AdminDaoImpl
而你的嘲笑根本就不会被使用。因此,您必须修改AdminDaoImpl
以允许您注入SimpleDateFormat
或编写测试,以便他们不知道AdminDaoImpl
使用SimpleDateFormat
。
就个人而言,我根本不会嘲笑SimpleDateFormat。相反,我会将其视为AdminDaoImpl
的内部实现细节。我会模拟结果集以返回日期,然后验证ElectionListResponse
是否具有预期日期。这看起来像这样:
// (I am using the deprecated constructor for simplicity)
java.sql.Date startDate = new java.sql.Date(2018, 6, 5);
Mockito.when(mockResultSet.getDate("startDate")).thenReturn(startDate);
ElectionListResponse response = adminDao.getElections('>' );
Election firstElection = response.getFirst() // Or whatever method(s) get you the first one
Assert.assertEquals("2018-06-05 00:00", firstElection.getStartDate());
这些测试证实Election
从结果集中正确映射了startDate
,但他们并不关心AdminDaoImpl
是如何做到的。
如果您正在模拟DateFormat,那么为什么要创建SimpleDateFormat对象。您应该在使用SimpleDateFormat对象的任何地方提供when()和thenReturn()。应该模拟所有依赖项,不存在实际的对象创建。
在DAO的单元测试中没有数据库交互,您可以轻松地模拟数据库层。
when(df.format("your_date").thenReturn(some_value);