首页 > 解决方案 > 使用 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

我尝试了几种方法来解决这个问题,但我无法让它可靠地工作。提前谢谢你的帮助。

标签: javaunit-testingjunitpowermockpowermockito

解决方案


代码示例未显示如何初始化time对象。time.getDate

对于此测试 - 您应该使用相同的种子值初始化time和,否则结果是不可预测的。Calendar.getInstance()


推荐阅读