在Dart单元测试中,如何模拟或验证打印调用?

Set*_*add 9 dart

在我的Dart单元测试中,如何验证是否调用了打印?

我正在为教程编写示例代码,我想测试它.许多样品print用于简单.我希望我的单元测试能够验证是否使用正确的输入调用了打印.

谢谢!

小智 6

更新: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']);
  }));
}

overridePrint(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(testFn);
};
Run Code Online (Sandbox Code Playgroud)


Jus*_*ani 5

我不认为unittest会添加任何特定的内容,但您可以覆盖测试范围内的任何顶级函数并捕获对日志的调用,例如:

var printLog = [];
void print(String s) => printLog.add(s);

main() {
  test('print', () {
    myFuncUnderTest();
    expect(printLog.length, 2);
    expect(printLog[0], contains('hello'));
    // etc...
  });
}
Run Code Online (Sandbox Code Playgroud)

  • 在我看来,这种方法闻起来很臭。 (2认同)