Home > Back-end >  Unit tests running in parallel in flutter when using GetIt
Unit tests running in parallel in flutter when using GetIt

Time:11-27

I am writing an flutter App and I am using GetIt for dependency injection.

When I write unit tests, I do something like this:

void main() {
  group("tests", () {
    test("test1", () {
      GetIt.I.reset();
      GetIt.I.registerSingleton(MyDependency());

      // Some code using GetIt.I<MyDependency>()
    });
    test("test2", () {
      GetIt.I.reset();
      GetIt.I.registerSingleton(MyDependency());

      // Some code using GetIt.I<MyDependency>()
    });
  });
}

When I run the tests one after the other, it works perfectly.

When I run all test at once, I get errors on the line GetIt.I<MyDependency>()... like this:

'package:get_it/get_it_impl.dart': Failed assertion: line 372 pos 7: 'instanceFactory != null': Object/factory with  type HttpActions is not registered inside GetIt. 

So my guess is, that the tests run in parallel and the setup of one test with GetIt.I.reset() conflicts with the setup of the other test.

So how can I solve this?

  • Can I somehow tell the tests, that they just cannot run in parallel?
  • Or is there some way of safely using GetIt in this context?

CodePudding user response:

I think your issue is not about running your tests in parallel but related to the fact that GetIt.I.reset() is an asynchronous method:

Implementation

Future<void> reset({bool dispose = true});

And as mentionned in the documentation of the package for this method:

[...] As dispose functions can be async, you should await this function.

Code Sample

I've made a new test sample based on the code you've provided and inspired by the unit tests written for the package and it seems to be working properly.

import 'package:flutter_test/flutter_test.dart';
import 'package:get_it/get_it.dart';
import 'package:so_tests/my_dependency.dart';

void main() {
  // This method provided by `flutter_test` is called before each test.
  setUp(() async {
    // Make sure the instance is cleared before each test.
    await GetIt.I.reset();
  });

  group('tests', () {
    test('test1', () {
      final getIt = GetIt.instance;
      getIt.registerSingleton(MyDependency());

      // Some code using getIt<MyDependency>()
    });

    test('test2', () {
      final getIt = GetIt.instance;
      getIt.registerSingleton(MyDependency());

      // Some code using getIt<MyDependency>()
    });
  });
}
  • Related