【问题标题】:JUnit Java Instant dependent testsJUnit Java Instant 依赖测试
【发布时间】:2019-10-21 17:46:33
【问题描述】:

我使用Instant.now() 来获取当前的UTC 毫秒,然后将其截断到最接近的小时。我所有的JUnit 都失败了,因为它们正在占用当前的系统时间。如何使Instant.now() 返回一个可以在JUnit 测试中提供的固定值。

public static Long getCurrentHour() {
    Instant now = Instant.now();
    Instant cH = now.truncatedTo(ChronoUnit.HOURS);
    return cH.toEpochMilli();
}

【问题讨论】:

标签: java junit java.time.instant


【解决方案1】:

您应该模拟静态方法 Instant.now() 以提供静态即时值。
你可以使用PowerMockito

@RunWith(PowerMockRunner.class)
@PrepareForTest(Instant.class)
public class TestClass {
    @Mock private Instant mockInstant;

    @Test
    public void getCurrentHour() throws Exception {
        PowerMockito.mockStatic(Instant.class);
        when(Instant.now()).thenReturn(mockInstant);
        when(mockInstant.truncatedTo(ChronoUnit.HOURS)).thenReturn(mockInstant);
        long expectedMillis = 999l;
        when(mockInstant.toEpochMilli()).thenReturn(expectedMillis);

        assertEquals(expectedMillis, YourClass.getCurrentHour());
    }
}

【讨论】:

    猜你喜欢
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 2012-08-23
    相关资源
    最近更新 更多