DEV Community

Cover image for How to test your Flutter Riverpod code with Mockito

Posted on

How to test your Flutter Riverpod code with Mockito

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.
void main() {
  // Create mock object.
  var mockCat = MockCat();

  testWidgets('Cat meows correctly', (WidgetTester tester) async {
    await tester.pumpWidget(ProviderScope(
      overrides: [
      child: MaterialApp(
        home: Consumer(builder: (context, ref, child) {
          final _cat =;
          return ElevatedButton(
            key: Key("make_sound"),
            onPressed: () async {
              try {
              } catch (err) {}
            child: const Text('Make Sound'),

    await tester.tap(find.byKey(Key("make_sound")));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)