写 Java 代码时,你大概也遇到过依赖当前时间的业务逻辑。订单 30 分钟后失效,优惠券只在黄金时段生效,cron 任务在午夜运行,token 过 1 小时刷新……给这些代码写单元测试时,怎么把时间往前“快进”或往后“倒带”呢?

这篇文章分享一下我在 mitisrv 项目里用的方法。它很简单,用不着引入任何笨重的框架。灵感来自 DZone 的文章 Mock Java Date/Time for Testing。

问题

假设你有这样的代码。

1
2
3
public boolean isExpired(Order order) {
  return LocalDateTime.now().isAfter(order.getExpiredAt());
}

测试时,你会遇到下面这些情况。

  • 把订单的 expiredAt 设为过去的时间 → 能测已过期的情况 ✓
  • 把订单的 expiredAt 设为未来的时间 → 能测尚未过期的情况 ✓
  • 可是怎么测试“刚好到期”的情况呢?或者怎么测试恰好在明天 00:00 运行的逻辑?

直接调用 LocalDateTime.now() 会让代码变得 不确定。测试在 11:59 运行时可能通过,到了 00:01 却可能失败。这简直是 CI/CD 的噩梦。

常见做法

1. 注入 java.time.Clock

Java 8 及以上版本推荐使用 Clock,并将它注入需要用到的地方。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class OrderService {
  private final Clock clock;

  public OrderService(Clock clock) {
    this.clock = clock;
  }

  public boolean isExpired(Order order) {
    return LocalDateTime.now(clock).isAfter(order.getExpiredAt());
  }
}

在测试中用 Clock.fixed(...) 把时间固定住。优点是实现干净,符合惯例。缺点是得改整个代码库,给每个类注入 Clock。如果项目已经很大,就会很麻烦。

2. 用 PowerMock 或 Mockito 模拟静态方法

1
2
3
4
try (MockedStatic<LocalDateTime> mocked = mockStatic(LocalDateTime.class)) {
  mocked.when(LocalDateTime::now).thenReturn(fixedTime);
  // test code
}

优点是生产代码无需改动。缺点是模拟静态方法速度慢,设置容易影响其他测试,而且 mockStatic 要从 Mockito 3.4 起才支持。如果代码交替调用 LocalDate.now()、Instant.now() 和 ZonedDateTime.now(),就得一个个模拟。

3. 用时间偏移量实现自定义工具类

这是我为 mitisrv 选的办法。写一个 Time 类来替代所有获取当前时间的方式,在类里存一个 deltaMillis,也就是“模拟时间”与系统实际时间之间的差值。

mitisrv 中的实现

下面是完整的 Time.java 文件。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.miti99.mitisrv.util.time;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.TimeZone;

public class Time {
  private static final TimeZone TIME_ZONE = TimeZone.getDefault();
  private static final ZoneId ZONE_ID = TIME_ZONE.toZoneId();
  private static volatile long deltaMillis = 0L;

  public static LocalDate currentDate() {
    return LocalDate.ofInstant(currentInstant(), ZONE_ID);
  }

  public static LocalTime currentTime() {
    return LocalTime.ofInstant(currentInstant(), ZONE_ID);
  }

  public static LocalDateTime currentDateTime() {
    return LocalDateTime.ofInstant(currentInstant(), ZONE_ID);
  }

  public static OffsetDateTime currentOffsetDateTime() {
    return OffsetDateTime.ofInstant(currentInstant(), ZONE_ID);
  }

  public static ZonedDateTime currentZonedDateTime() {
    return ZonedDateTime.ofInstant(currentInstant(), ZONE_ID);
  }

  public static Instant currentInstant() {
    return Instant.ofEpochMilli(currentTimeMillis());
  }

  public static long currentTimeMillis() {
    return System.currentTimeMillis() + deltaMillis;
  }

  public static void useMockTime(LocalDateTime dateTime, ZoneId zoneId) {
    deltaMillis = dateTime.atZone(zoneId).toInstant().toEpochMilli() - System.currentTimeMillis();
  }

  public static void useSystemDefaultZoneClock() {
    deltaMillis = 0L;
  }
}

有几个地方值得留意。

  • 所有获取时间的 API(currentDate、currentDateTime、currentInstant 等)都走同一个方法 currentTimeMillis()。只需要在一处模拟时间,整个系统的时间就能保持一致。
  • deltaMillis 是 volatile,保证不同线程能立即看到改动。这对多线程环境中的测试很重要。
  • useMockTime() 不会冻结时间,只是将它平移。比如把模拟时间设为 2026-01-01 00:00:00 后,如果现实中过了 5 秒,Time.currentDateTime() 就会返回 2026-01-01 00:00:05。这是它和 Clock.fixed() 的重要区别,时间依然往前走,只是起点变了。
  • useSystemDefaultZoneClock() 会恢复实际时间。在 @AfterEach 中调用它,测试用例之间就不会互相影响。

用法

在生产代码中,把 LocalDateTime.now() 换成 Time.currentDateTime()。

1
2
3
public boolean isExpired(Order order) {
  return Time.currentDateTime().isAfter(order.getExpiredAt());
}

测试代码可以这样写。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@Test
void orderShouldBeExpiredAfter30Minutes() {
  Order order = new Order();
  order.setExpiredAt(LocalDateTime.of(2026, 1, 1, 12, 30, 0));

  // 把时间“快进”到 12:31
  Time.useMockTime(
      LocalDateTime.of(2026, 1, 1, 12, 31, 0),
      ZoneId.systemDefault()
  );

  assertTrue(service.isExpired(order));

  Time.useSystemDefaultZoneClock(); // reset
}

用 @AfterEach 确保测试结束后重置时间。

1
2
3
4
@AfterEach
void tearDown() {
  Time.useSystemDefaultZoneClock();
}

做法对比

对比项注入 ClockmockStatic自定义 Time 工具类
是否要改生产代码改动多(注入 Clock)无需改动一次性改动(替换 .now())
框架依赖无Mockito 3.4+无
测试速度快慢快
支持时间继续流动否(Clock.fixed)否是
线程安全是是(作用域内)是(volatile)
符合 Java 惯例✓✓✓✓✓

自定义 Time 工具类的缺点

没有哪种方案是完美的。这种做法也有几个弱点。

  • 全局状态。 deltaMillis 是 static 的。如果在同一个 JVM 里并行运行测试,各测试就会互相干扰。确实需要并行时,得把测试框架配置为在独立 JVM 中运行每个测试类,或者用 ThreadLocal 替换 volatile。
  • 需要改动整个代码库。 要去掉对 LocalDateTime.now() 的直接调用。第三方库要是调用了 .now(),这个工具类也控制不了。
  • 不符合 Java 惯例。 刚加入项目的人看到 Time.currentDateTime() 取代了 LocalDateTime.now(),可能会觉得意外。

什么时候该选哪种做法?

  • 新项目、规模小,团队熟悉依赖注入。 按惯例注入 Clock。
  • 遗留项目,希望避免大范围重构。 在每个测试中局部使用 mockStatic,接受较慢的速度。
  • 希望实现简单、能控制时间流动,并且串行运行测试的项目。 像 mitisrv 一样使用自定义 Time 工具类。

对我来说,Time 工具类简单、好懂、好维护,也不用再学一个框架。代价是写代码时要守规矩,每次都把 LocalDateTime.now() 换成调用 Time.xxx()。在审查 PR 时用一条简单的 lint 规则,就足以守住这个约定。

参考资料