A dead-simple example of how to test a riverpod provider with Mockito. What we have here is a simple class of cat
that has a method sound. This class has been used via a change notifier provider. On the app, we have an elevated button that on tapping calls the sound
method.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'cat_test.mocks.dart';
class Cat extends ChangeNotifier {
String sound() => "Meow";
}
final catProvider = ChangeNotifierProvider<Cat>((ref) {
return Cat();
});
// Annotation which generates the cat.mocks.dart library and the MockCat class.
@GenerateMocks([Cat])
void main() {
// Create mock object.
var mockCat = MockCat();
when(mockCat.sound()).thenReturn('Meow');
testWidgets('Cat meows correctly', (WidgetTester tester) async {
await tester.pumpWidget(ProviderScope(
overrides: [
catProvider.overrideWithValue(mockCat),
],
child: MaterialApp(
home: Consumer(builder: (context, ref, child) {
final _cat = ref.watch(catProvider);
return ElevatedButton(
key: Key("make_sound"),
onPressed: () async {
try {
_cat.sound();
} catch (err) {}
},
child: const Text('Make Sound'),
);
}),
),
));
await tester.tap(find.byKey(Key("make_sound")));
verify(mockCat.sound()).called(1);
});
}
Top comments (0)