2

So let's say I have a Counter class like this

class Counter extends ChangeNotifier {
  int _i = 0;

  int get myCounter => _i;
  
  void increment() {
    _i++;
    notifyListeners();
  }

  void decrement() {
    _i--;
    notifyListeners();
  }
}

I want to write a test file for it, so I expose its instance like this. The problem is, after I expose it, how do I access the instance of the class I just created? Like say, I increased _i value through a button, how will I access the instance that is created by Provider in order to test it?

IcyHerrscher
  • 391
  • 3
  • 9

2 Answers2

1

I was looking to do the same but then I found this answer https://stackoverflow.com/a/67704136/8111212

Basically, you can get the context from a widget, then you can use the context to get the provider state

Btw, you should test a public variable like i instead of _i

Code sample:

testWidgets('showDialog', (WidgetTester tester) async {
  await tester.pumpWidget(MaterialApp(home: Material(child: Container())));
  final BuildContext context = tester.element(find.byType(Scaffold)); // It could  be  final BuildContext context = tester.element(find.byType(Container)) depending on your app

  final Counter provider = Provider.of<Counter>(context, listen: false);
  expect(provider.i, equals(3));
});

Thien Phan
  • 358
  • 4
  • 8
0

You first initialize the Provider in your main.dart file using

ChangeNotifierProvider

after that you can use the class anywhere in your code by either using the Consumer widget or by using:

final counter = Provider.of<Counter>(context)

Here is a good post/tutorial about how to use Provider

BJW
  • 925
  • 5
  • 15
  • Yes, thank you. But this is in Flutter test, There's no way to use context to access it. Says, I increase the `_i` value, there's no way for me to verify whether It will increase or not because I can't access the instance that is created by `Provider/ChangeNotifierProvider`. – IcyHerrscher Oct 04 '21 at 13:46