在以下设置下
@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/