调用 SimpleDateFormat 方法时模拟 Date()

Mock Date() when you call SimpleDateFormat method

在以下设置下

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

我的 src 上有这个

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)

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

"correct" 方法:编写可测试代码。并且直接调用 new 有时会导致难以测试的代码。然后人们需要拿出大 PowerMock(ito) 锤子来修复它。

或者,考虑学习如何编写可测试的代码;开始 here

在您的情况下,您可以在测试中为您的代码提供一个小工厂,为您生成 "current" 日期对象。您使用依赖注入将该工厂放入您的 class 测试中;为了测试,你模拟了那个工厂。导致 zero 需要模拟调用 new.

java.time

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

取代

Clock

java.time 类 允许您通过 Clock 的替代实现以进行测试。

Clock 甚至附带了一些已经为您构建的替代实现。一个人可以冻结到特定的固定时刻。另一个保持时间但从真实时间偏移指定的量。其他按整秒、整分钟或您指定的任何数量递增。