java - 调用 SimpleDateFormat 方法时模拟 Date()

标签 java junit mocking mockito simpledateformat

在以下设置下

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class myTest {

我的源代码中有这个

DateFormat dataformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentdate = dataformat.format(new Date());

我知道 Date.getTime() 方法将被调用。

我在我的测试代码上尝试过这个。

final Date date = Mockito.mock(Date.class);
Mockito.when(date.getTime()).thenReturn(dateLongValue);

但是什么也没发生。 我也尝试过像这样的模型

Mockito.when(date.format(new Date())).thenReturn(dateStringValue);

但是得到了

java.lang.NullPointerException
at java.text.DateFormat.format(DateFormat.java:346)

这可能很容易,但我没有运气。任何建议将不胜感激。

最佳答案

java.time

您正在使用麻烦的旧遗留日期时间类,现在已被 java.time 取代。类。

时钟

java.time 类允许您传递 Clock 的替代实现出于测试目的。

Clock 甚至附带了一些已经为您构建的替代实现。一个人可以卡住在某个特定的固定时刻。另一种方法保留时间,但与真实时间偏移指定的量。其他则按整秒、整分钟或您指定的任何数量递增。

关于java - 调用 SimpleDateFormat 方法时模拟 Date(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39381559/

相关文章:

php - 为什么 phpunit 不在模拟类中运行 __destruct() 以及如何强制运行它?

java - 如何用Java生成JUnit测试用例?

java - 删除数据库中的条目并验证它是否已被删除 - 删除后仍然找到该条目

java - 如何模拟测试下方法调用的方法

java - Web 服务:远程接口(interface)与请求/响应方案

java - 使用 junit 测试输入

c# - 在犀牛中混合 stub 和模拟

java - 如何在生产中部署 H2O flow pojo 文件

java - Spring - 如何在 View 之间传递消息?

java - 从 SQL 中同一行的另一列获取值