How to correctly override in tests the provider generated by Riverpod?

499 Views Asked by At

I have the repository and I generate provider for this repository like this:

@riverpod
class Repository extends _$Repository {
  @override
  String? build() {
    return null;
  }

  Future<void> fetchData() async {
    state = "Hello World!";
  }
}

I want to test my application. In test I want to mock the provider of this repository. But I have message from riverpod_lint: Providers which are overridden in a non-root ProviderContainer/ProviderScope should specify dependencies..

My test looks like this:

@riverpod
class MockedRepository extends _$MockedRepository implements Repository {
  @override
  String? build() {
    return null;
  }

  Future<void> fetchData() async {
    state = "Hello Mocked World!";
  }
}

void main() {
  testWidgets('override repositoryProvider', (tester) async {
    await tester.pumpWidget(
      ProviderScope(
        overrides: [
          repositoryProvider.overrideWith(() => MockedRepository()),
        ],
        child: const App(),
      ),
    );
  });
}

I found one solution: when I added @Riverpod(dependencies: []) annotation instead of @riverpod annotation in original Repository class, riverpod_lint stop messaging. But I don't understand why should I correct my original class for test purposes. Should I always describe dependencies? Maybe there is a way to make ProviderContainer/ProviderScope root in tests?

0

There are 0 best solutions below