Dart/Flutter: Share common setUp/tearDown methods among test suites

1,654

Create a file called flutter_test_config.dart in the same directory as your test (or at a higher level, it'll affect all tests in that directory and below).

In that file, you can then call the setUp and tearDown methods before your test file's main method runs:

import 'dart:async';
import 'package:flutter_test/flutter_test.dart';

Future<void> main(FutureOr<void> Function() testMain) async {
  setUp(() {
    print('Shared setUp');
  });

  tearDown(() {
    print('Shared tearDown');
  });

  await testMain();
}

Documentation: https://api.flutter.dev/flutter/flutter_test/flutter_test-library.html

Share:
1,654
daveoncode
Author by

daveoncode

Updated on December 17, 2022

Comments

  • daveoncode
    daveoncode over 1 year

    Is there a way to share common setUp/tearDown methods and other helper methods among tests in Dart/Flutter? Usually in other languages/frameworks, like Java or Python, tests are defined in classes which can be extended, but the way Dart approaches testing by using functions inside a main method lets me perplexed. For instance I'm testing io methods, I have the following piece of code in my test:

      Directory tempDir;
    
      setUp(() async {
        tempDir = await Directory.systemTemp.createTemp();
    
        const MethodChannel('plugins.flutter.io/path_provider').setMockMethodCallHandler((MethodCall methodCall) async {
          if (methodCall.method == 'getApplicationDocumentsDirectory') {
            return tempDir.path;
          }
          return null;
        });
      });
    
      tearDown(() async {
        tempDir.delete(recursive: true);
      });
    

    If it were any other language I would create a base class or a mixin called TempDirTestCase in which to put the code for the creation/deletion of the temporary directory, then each suite that need such functions would have just to inherit from it... but what I'm supposed to do in dart/flutter to reuse the code and avoid copy/paste?