跨平台开发 / 系统课时
控制时间依赖避免真实等待
控制时间依赖避免真实等待
重试、缓存过期和定时任务常把测试拖慢,因为代码直接读取系统时间或真实等待。解决办法不是把等待时间调短,而是把“现在几点”和“等待多久”抽成可替换依赖,让测试主动推进条件并立即验证结果。
学习目标
- 识别
DateTime.now()与真实延迟对测试速度和稳定性的影响 - 将时钟与等待函数注入业务逻辑,在测试中替换为可控实现
- 不经过真实等待验证过期边界、重试次数与退避请求
时间依赖为什么会拖慢测试
如果过期逻辑直接调用 DateTime.now(),测试只能围绕真实时钟组织数据;如果重试逻辑直接执行 Future.delayed(),验证三次重试可能真的要等数秒。测试因此变慢,还容易在时间边界、机器负载或并行执行时出现偶发失败。
更稳定的做法是把时间当成普通依赖:业务代码只向 Now 询问当前时间,只向 Sleep 请求等待。生产环境连接系统实现,测试则提供固定时钟和“只记录、不休眠”的等待函数。
把时钟和等待函数变成依赖
下面是一个完整测试文件。ExpiryPolicy 不直接读取系统时钟,retry 也不直接调用真实延迟,因此测试可以精确控制时间和重试过程。
import 'package:test/test.dart';
typedef Now = DateTime Function();
typedef Sleep = Future<void> Function(Duration delay);
class ExpiryPolicy {
ExpiryPolicy({
required this.createdAt,
required this.ttl,
required this.now,
});
final DateTime createdAt;
final Duration ttl;
final Now now;
// 到达过期时刻本身就视为过期,便于明确边界行为。
bool get isExpired => !now().isBefore(createdAt.add(ttl));
}
Future<T> retry<T>({
required Future<T> Function() action,
required int maxAttempts,
required Duration delay,
required Sleep sleep,
}) async {
if (maxAttempts < 1) {
throw ArgumentError.value(maxAttempts, 'maxAttempts', 'must be >= 1');
}
for (var attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await action();
} catch (_) {
// 最后一次失败直接向调用者传播,不再产生多余等待。
if (attempt == maxAttempts) rethrow;
await sleep(delay);
}
}
throw StateError('unreachable');
}
void main() {
test('过期判断使用可控时钟', () {
var current = DateTime.utc(2026, 9, 16, 10);
final policy = ExpiryPolicy(
createdAt: current,
ttl: const Duration(minutes: 5),
now: () => current,
);
expect(policy.isExpired, isFalse);
// 直接推进测试时钟,不等待现实中的五分钟。
current = current.add(const Duration(minutes: 5));
expect(policy.isExpired, isTrue);
});
test('重试会请求等待但测试不真实休眠', () async {
var attempts = 0;
final requestedDelays = <Duration>[];
final result = await retry<String>(
action: () async {
attempts++;
if (attempts < 3) throw StateError('temporary');
return 'ok';
},
maxAttempts: 3,
delay: const Duration(seconds: 2),
sleep: (duration) async {
// 测试只记录等待请求,不把真实时间浪费在 sleep 上。
requestedDelays.add(duration);
},
);
expect(result, 'ok');
expect(attempts, 3);
expect(requestedDelays, [
const Duration(seconds: 2),
const Duration(seconds: 2),
]);
});
}预期结果
两个测试都通过;第二个测试记录两次 2 秒延迟请求,但不发生真实等待。将文件保存为 test/time_dependency_test.dart 后执行:
dart test test/time_dependency_test.dart预期输出
<TIME> +2: All tests passed!<TIME> 会随机器和 Dart SDK 环境变化。生产代码可以把 DateTime.now 作为时钟传入,并用 (delay) => Future<void>.delayed(delay) 连接真实等待;测试只替换这两个依赖,不需要在业务代码里增加“测试模式”分支。
什么时候使用虚拟时间工具
依赖注入适合重试、过期、退避这类业务级时间规则,因为依赖边界明确,测试也最容易读懂。若被测对象内部同时包含多个 Timer、Future.delayed、超时 Future 或按时间触发的 Stream,逐个注入等待函数会变得笨重,此时可以使用 package:fake_async 在受控环境中推进虚拟时间。
控制异步计时与控制“当前日期时间”是两个问题。即使使用虚拟时间工具,也应避免在核心业务代码里到处散落 DateTime.now();集中通过可替换时钟读取时间,过期边界和时间窗口才容易稳定验证。
避免把不稳定性写进测试
不要在测试里用真实 Future.delayed() 等待“差不多应该发生”的事件,也不要用当前系统时间再加几毫秒制造过期边界。前者让测试套件越来越慢,后者容易形成竞争条件。
时间相关测试应直接断言业务事实:在某个确定时刻是否过期、失败几次后是否成功、每次重试请求了多长延迟。这样既验证了规则,也把测试耗时从真实时间长度中解耦出来。