gpt4 book ai didi

java - 在 JUnit 测试中模拟日期格式 (SimpleDateFormat)

转载 作者:行者123 更新时间:2023-12-02 11:09:25 25 4
gpt4 key购买 nike

我正在尝试测试使用 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 是一个最终函数,不能被 mock 。那里有一些解决方法,但对我不起作用。我不确定我是否正确实现了这些解决方法。

您能给我提供修复此 NullPointer 的代码吗?提前致谢!

最佳答案

首先,我没有看到任何 mock 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'") 可能让你过去异常(exception)。不过,看起来您正在 AdminDaoImpl 中创建一个真正的 SimpleDateFormat,而您的模拟的根本不会被使用。因此,您必须修改 AdminDaoImpl 以允许注入(inject) SimpleDateFormat 或编写测试,以便它们不知道 AdminDaoImpl 使用 SimpleDateFormat.

就我个人而言,我根本不会 mock 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());

这些测试确认 ElectionstartDate 从结果集中正确映射,但它们根本不关心 AdminDaoImpl 如何映射可以。

关于java - 在 JUnit 测试中模拟日期格式 (SimpleDateFormat),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50699544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com