How to write multiple unittests in dart in multiple files?
There is a tool that does exactly that, Dart Test Runner. An excerpt from that page:
Dart Test Runner will automatically detect and run all the tests in your Dart project in the correct environment (VM or Browser).
It detects any test writen in a file suffixed with _test.dart
where your test code is inside a main()
function. It doesn't have any problem detecting and running unittest tests.
It's pretty easy to install it and run it. Just two commands:
$ pub global activate test_runner
$ pub global run test_runner
For more options, please check Dart Test Runner page.
It is common to separate tests into multiple files. I am including an example of how you can do that.
Imagine that you have 2 files with tests, foo_test.dart, bar_test.dart that contain tests for your program. foo_test.dart could look something like this:
library foo_test;
import 'package:unittest/unittest.dart';
void main() {
test('foo test', () {
expect("foo".length, equals(3));
});
}
And bar_test.dart could look something like this:
library bar_test;
import 'package:unittest/unittest.dart';
void main() {
test('bar test', () {
expect("bar".length, equals(3));
});
}
You could run either file, and the test contained in that file would execute.
The, I would create something like an all_tests.dart file that would import the tests from foo_test.dart and bar_test.dart. Here is what all_tests.dart could look like:
import 'foo_test.dart' as foo_test;
import 'bar_test.dart' as bar_test;
void main() {
foo_test.main();
bar_test.main();
}
If you executed all_tests.dart, both the tests from foo_test.dart and bar_test.dart would execute.
One thing to note: for all this to work, you need to declare foo_test.dart and bar_test.dart as libraries (see the first line of each file). Then, in all_tests.dart, you can use import syntax to fetch the contents of the declared libraries.
This is how I organize most of my tests.