How to unit test a class that is created by provider?

Viewed 252

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?

2 Answers

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));
});

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

Related