java - 使用 PowerMock 进行单元测试,比较秒时的精度问题
问题描述
我正在尝试使用 powermock 对时间函数进行单元测试,但是在将当前时间与系统时钟进行比较时,有时我无法通过 assertEquals()。预计时间为 2 秒。这是我的参考代码:
@RunWith(PowerMock Runner.class)
@PrepareForTest({Calendar.class, time.class})
public class TEST {
@Test
public void testTime() {
PowerMockito.mockStatic(Calendar.class);
Mockito.when(Calendar.getInstance()).thenReturn(calendarInstance);
SimpleDateFormat sdf = new SimpleDateFormat(DD_DOT_MM_DOT_YYY);
assertEquals(sdf.format(calendarInstance.getTime()), time.getDate(DD_DOT_MM_DOT_YYYY)); }
}
//inside the time.getDate function
public static String getDate(String format) {
DateFormat dateFormat = new SimpleDateFormat(format);
Date date = new Date();
return dateFormat.format(date);
}
这是我有时得到的指示失败的 Junit 输出:
org.junit.ComparisonFailure:
Expected :20:43:18
Actual :20:43:20
我尝试了几种方法来解决这个问题,但我无法让它可靠地工作。提前谢谢你的帮助。
解决方案
代码示例未显示如何初始化time
对象。time.getDate
对于此测试 - 您应该使用相同的种子值初始化time
和,否则结果是不可预测的。Calendar.getInstance()
推荐阅读
- scala - 尽管连接条件很重要,但 Spark 检测到笛卡尔积
- android - Starting session in Appium
- r - 在 Shiny Dashboard 中强制刷新
- r - 解析 HPO obo 文件以提取外部参照
- ios - 如何在 IOS 中使用 TextureAtlas 从 Internet 加载纹理?
- ios - 如何限制 UICollectionView 的单元格显示数量 - swift
- c# - COM 端口通讯问题,Text To ASCII
- javascript - 标识符不是驼峰式的
- android - 如何制作可点击的动画文本视图?
- php - Laravel/Vue.js - 试图获取非对象的属性。可以在 Vue 中访问它,但不能在 Laravel 中访问