在我的Dart单元测试中,如何验证调用了print?
我正在为教程编写示例代码,我想对其进行测试.为简单起见,许多示例使用print
.我希望我的单元测试能够验证使用正确的输入调用print.
谢谢!
在我的Dart单元测试中,如何验证调用了print?
我正在为教程编写示例代码,我想对其进行测试.为简单起见,许多示例使用print
.我希望我的单元测试能够验证使用正确的输入调用print.
谢谢!
更新:ZoneSpecification允许覆盖print
函数.通过在自定义区域内运行测试代码,您可以捕获对print
函数的调用.例如,下面的测试将所有打印消息重定向到内存列表log
中:
import 'dart:async';
import 'package:test/test.dart';
var log = [];
main() {
test('override print', overridePrint(() {
print('hello world');
expect(log, ['hello world']);
}));
}
void Function() overridePrint(void testFn()) => () {
var spec = new ZoneSpecification(
print: (_, __, ___, String msg) {
// Add to log instead of printing to stdout
log.add(msg);
}
);
return Zone.current.fork(specification: spec).run<void>(testFn);
};