我为我的一个 Dart 库编写了一组单元测试,但是我希望能够过滤这些单元测试,以便在我的连续构建期间只允许某些单元测试运行。我注意到 unittest api 允许这样做,但我找不到任何示例。
最佳答案
您可以通过创建自定义配置并使用 filterTests()
来过滤运行的测试。
import "package:unittest/unittest.dart";
class FilterTests extends Configuration {
get autoStart => false; // this ensures that the tests won't just run automatically
}
void useFilteredTests() {
configure(new FilterTests()); // tell configure to use our custom configuration
ensureInitialized(); // needed to get the plumbing to work
}
然后,在 main()
中,您使用 useFilterTests()
,然后使用字符串或正则表达式调用 filterTests()
进行测试你想跑。
void main() {
useFilteredTests();
// your tests go here
filterTests(some_string_or_regexp);
runTests();
}
描述与 filterTests()
的参数相匹配的测试将运行;其他测试不会。我写了一个blog post关于使用 filterTests()
,您可能会发现它很有用。
过滤测试的另一种方法是将它们分成多个库,然后 import()
只有那些你想运行其测试的库的 main()
函数。
因此,想象一个包含一些测试的库:
library foo_tests;
import "package:unittest/unittest.dart";
void main() {
// some tests for foo()
}
另一个包含其他测试:
library bar_tests;
import "package:unittest/unittest.dart";
void main() {
// some tests for bar()
}
您可以通过从每个库中导入 main()
来将测试运行器组合在一起。在 my_tests.dart
中,您可以这样做来运行所有测试:
import "package:unittest/unittest.dart";
import "foo_tests.dart" as foo_tests;
import "bar_tests.dart" as bar_tests;
void main() {
foo_tests.main();
bar_tests.main();
}
如果您只想运行foo_tests
或bar_tests
,您可以只导入一个。这将有效地创建一个过滤器。这是一个simple working example这些导入是如何工作的
关于testing - Dart 单元测试过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14387835/