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!
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.
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.
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.
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...
});
}
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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With