test method

Future<void> test({
  1. Map<String, String>? environment,
  2. bool includeParentEnvironment = true,
  3. bool runInShell = true,
  4. ProcessStartMode mode = ProcessStartMode.inheritStdio,
})

Test all files inside this Dart package.

It will detect whether a Dart test file in the testDirectory is a Dart or Flutter test by detecting its imports with containsImport. When such file uses package:test/test.dart, it will use the dart test command, and when such file uses package:flutter_test/flutter_test.dart, it will use the flutter test command.

  1. There's parameters like Process.run to specify environment.
  2. It will output by default, as the mode is default to ProcessStartMode.inheritStdio. When it's unnecessary to output, you can set the mode parameter to ProcessStartMode.detached.

Implementation

Future<void> test({
  Map<String, String>? environment,
  bool includeParentEnvironment = true,
  bool runInShell = true,
  ProcessStartMode mode = ProcessStartMode.inheritStdio,
}) async {
  final allTestFiles = testDirectory
      .listSync(recursive: true)
      .whereType<File>()
      .where((file) => file.path.endsWith('_test.dart'));

  // Classify all test files into Dart and Flutter test files.
  final dartTestFiles = <File>[];
  final flutterTestFiles = <File>[];
  for (final file in allTestFiles) {
    final code = file.readAsStringSync();
    final dartTest = containsImport(code, _dartTestImport);
    final flutterTest = containsImport(code, _flutterTestImport);
    if (dartTest) dartTestFiles.add(file);
    if (flutterTest) flutterTestFiles.add(file);
  }

  // Run dart and flutter tests separately.
  final dartPaths = dartTestFiles.map((file) => file.path).toList();
  final flutterPaths = flutterTestFiles.map((file) => file.path).toList();
  Future<int> run(String executable, List<String> arguments) => this.run(
    executable,
    arguments,
    environment: environment,
    includeParentEnvironment: includeParentEnvironment,
    runInShell: runInShell,
    mode: mode,
  );
  if (dartTestFiles.isNotEmpty) await run('dart', ['test', ...dartPaths]);
  if (flutterTestFiles.isNotEmpty) {
    await run('flutter', ['test', ...flutterPaths]);
  }
}