Seth Ladd
Seth Ladd

Reputation: 120639

How do I mock or verify a call to print, in Dart unit tests?

In my Dart unit tests, how do I verify that print was called?

I'm writing sample code for tutorials, and I want to test it. Many samples using print for simplicity. I'd like my unit tests to verify that print is called with the right input.

Thanks!

Upvotes: 13

Views: 3756

Answers (3)

jsilverdev
jsilverdev

Reputation: 21

Use the prints Matcher:

import 'package:test/test.dart';

void main() {
  test(
    'test print',
    () {
      const text = "IWuUtfAiAN";
      expect(() => print(text), prints("$text\n"));
    },
  );
}

Upvotes: 0

user1704813
user1704813

Reputation: 201

Update: ZoneSpecification allows overriding the print function. By running code-under-test inside a custom zone you can capture calls to print function. For example, the following test redirects all print messages into an in-memory list 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);
};

Upvotes: 13

Justin Fagnani
Justin Fagnani

Reputation: 11191

I don't think unittest adds anything specific for this, but you can override any top-level function in the scope of your test and capture calls to a log, for example:

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

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

Upvotes: 6

Related Questions