It's often the case that you need to do some sort of cleanup after every test. For instance, cleaning the database.
QUESTION:
Is there a way to attach global tearDown and setUp functions when using the unittest library? It'd be even better to be able to define around advice:
unittest.around((test){
//doing setup
test();
//doing cleanup
});
Of course, the bug needs to be fixed first :-)
Then you would do this as Justin says' using non-anonymous functions that you can upcall explicitly. It seemed to me that this was the best way of providing maximum flexibility without encumbering the unit test library with a lot of convoluted setup/teardown logic.
If you want to do test suite setup/teardown, you could do that with an initial/final "test" in the group:
group('test suite', () {
test('Set up suite', () { ... });
test('Test 1', () { ... });
...
test('Test n', () { ... });
test('Tear down suite', () { ... });
});
It's not ideal, but it is a solution.
It's worth pointing out that internally, groups are not actually represented as a hierarchy. All we are really doing is keeping a stack with the current setUp/tearDown functions so we can associate each test case with the appropriate ones, and concatenating the group names and test name to make the final name for the test case. We are not building a tree data structure, so we don't have a good way of doing upcalls implicitly (we could create closures on the fly that upcall one level, and use those as the actual setUp/tearDown functions, but that's a bit fugly).
You can do it manually, as Gram alludes to in the bug:
main() {
topSetup() {
// ...
}
setUp(topSetup);
group('group', () {
setUp(() {
topSetup();
// ...
});
test('test', () {
// ...
});
});
}
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