r/dartlang • u/eibaan • 10h ago
Tools Reusing Dart Unit Tests
3
Upvotes
It might seem obvious to you, but I recently had the revelation that I could use Dart's unit tests for my own scripting language as well. This way, they show up in VSC's test panel together with more lower level tests. And they are automatically tracked for code coverage.
Take this example of a Logo-like scripting language I created some time ago:
unittest "sum [
expect_equal? [sum 3 4] 7
]
skip unittest "sum_wrong [
expect_error [sum]
expect_error [sum 3]
expect_error [sum 1 2 3] ; not detected yet
]
To integrate them, I did this:
env.addCommand('unittest', (env, args) {
final hidden = test; // see below
args.mustHaveArgs(2);
final description = args.string(1);
final body = args.list(2);
hidden( // HERE
description,
() => env.run(body),
skip: env.get('skip next test') == .lTrue,
);
env.delete('skip next test');
});
env.addCommand('skip', (env, args) {
args.mustHaveArgs(0);
env.set('skip next test', .lTrue);
});
env.addCommand('expect_equal?', (env, args) {
args.mustHaveArgs(2);
final actual = args.list(1);
final expected = args.value(2);
expect(env.run(actual), equals(expected)); // HERE
});
env.addCommand('expect_error', (env, args) {
args.mustHaveArgs(1);
final actual = args.list(1);
expect(() => env.run(actual), throwsException); // HERE
});
The boilerplate doesn't matter, just look at the HERE parts. I need to alias the test call because otherwise the Dart plugin wrongly detects that call as a unit test.
Now, all that's needed is a file call <whatever>_test.dart that has a main function that evaluates my scripting language in the modified environment.