Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dart

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!

like image 578
Seth Ladd Avatar asked Feb 08 '13 01:02

Seth Ladd


People also ask

How do you make a mock Dart?

Create a test file with a mock http. dart in the root test folder. Add the annotation @GenerateMocks([http. Client]) to the main function to generate a MockClient class with mockito . The generated MockClient class implements the http.

How do you print a statement in Dart?

This method acts as the entry point to the application. A Dart script needs the main() method for execution. print() is a predefined function that prints the specified string or value to the standard output i.e. the terminal.

How do you use mock in flutter?

In Mockito, we generate mocks by adding the annotation @GenerateMocks([classes]) to the beginning of the main method. This informs the build runner to generate mocks for all the classes in the list. Next, open the terminal and run the command flutter pub run build_runner build to start generating mocks for the classes.


2 Answers

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...
  });
}
like image 141
Justin Fagnani Avatar answered Oct 07 '22 05:10

Justin Fagnani


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);
};
like image 45
user1704813 Avatar answered Oct 07 '22 07:10

user1704813