java - 在 JUnit 测试中模拟日期格式(SimpleDateFormat)
问题描述
我正在尝试测试使用 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
它是如何映射的。
推荐阅读
- php - PHP exec命令在脚本中不起作用
- java - 使用 Jackson 库的 Bukkit ItemStack 序列化
- mysql - 如何在 mysql 5.7 中实现行号功能?
- node.js - 如何正确解决nodejs中的promise
- javascript - 可选地从基类的子类继承
- python - 如何查看tensorflow张量keras输入层的内容?
- javascript - 获取在其数组中具有和不具有某些属性的对象的名称
- database - 无法从 CDB 容器中删除 PDB 快照
- django - import_data() missing 1 required positional argument: 'dataset' -
- selenium - Selenium“chrome 正在由自动化软件控制”消息卡在我的浏览器中