4

I want to override my StateNotifierProvider state manually for testing. Overriding providers can be done using ProviderContainer or ProviderScope. But it only gives the option to override the notifier, not the state.

My question is how should I override the state?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
NirmalCode
  • 2,140
  • 1
  • 14
  • 19

1 Answers1

2

if you want to override the providers. For instance, when you want to test a specific category. In this case, we can override the ScopedProvider with a value. Then, in the ProviderScope, we can choose which provider to override and choose which value to override

testWidgets('Override the current scope', (tester) async {
    await tester.pumpWidget(ProviderScope(
        overrides: [
          selectedCategory.state.overrideWithValue(Category("Pear", Colors.green))
        ],
        child: HookBuilder(builder: (context) {
          return MaterialApp(home: CategoryWidget());
        })));

    expect((tester.firstWidget(find.byType(Text)) as Text).style.color,
        Colors.green);
    expect((tester.firstWidget(find.byType(Text)) as Text).data, "Pear");
  });
Omar Mahmoud
  • 2,902
  • 1
  • 14
  • 22
  • 1
    Thanks for answering. Adding a function to every StateNotifierProvider just for testing is a lot of unnecessary work. Also, it may lead to misusing that function. I'm looking for a way without adding anything to existing providers. – NirmalCode Aug 28 '21 at 18:44
  • 2
    The issue is with `StateNotifierProvider`. `overrideWithValue` only allows `Notifiers` as value. Can't override the state. – NirmalCode Aug 30 '21 at 15:09
  • this article helped me may it help you https://bartvwezel.nl/flutter/flutter-riverpod-testing-example/ – Omar Mahmoud Aug 30 '21 at 15:12
  • I am also having this issue, I cannot find a way to override the state of a StateNotifierProvider which returns a class that extends StateNotifier. The only override available is .notifier. I have posted an example of my code and state architecture here: https://stackoverflow.com/questions/70011054/riverpod-testing-how-to-mock-state-with-statenotifierprovider – Matthew Rideout Nov 17 '21 at 20:23