An example of how to mock state for testing widgets when using riverpod StateNotifierProvider

Overview

Testing Riverpod StateNotifierProvider

An example of how to mock state for testing widgets when using riverpod StateNotifierProvider.

These tests work without Mocktail / Mockito

Quick Details

  • Model: Counter class created with Freezed
  • State: CounterNotifier extends StateNotifier
  • Provider: counterProvider is a StateNotifierProvider

Important For Testability of StateNotifierProvider

When testing Flutter widgets, one may want to mock a predefined state in order to test how widgets render for a given state. For example, a widget may need to show or hide depending on user role, which could be part of a user object stored in state. Our test allows us to ensure this important conditional rendering does not break with future code changes.

In this simplified example, we are using a counter to test whether a widget renders when the count is even.

This repository exists as an example for how to architect your StateNotifier and its constructor such that a mocked provider and predefined state can be used by the test widget.

Below is a breakdown of what is happening in this repository.

Explanation

The Test Widget

Widget isEvenTestWidget(StateNotifierProvider<CounterNotifier, Counter> mockProvider) {
    return ProviderScope(
      overrides: [
        counterProvider.overrideWithProvider(mockProvider),
      ],
      child: const MaterialApp(
        home: ScreenHome(),
      ),
    );
  }

This test widget for our home screen uses the overrides property of ProviderScope() in order to override the provider used in the widget.

When the home.dart ScreenHome() widget calls Counter counter = ref.watch(counterProvider); it will use our mockProvider instead of the "real" provider.

The isEvenTestWidget() mockProvider argument is the same "type" of provider as counterProvider().

The Test

testWidgets('If count is even, IsEvenMessage is rendered.', (tester) async {
  // Mock a provider with an even count
  final mockCounterProvider =
      StateNotifierProvider<CounterNotifier, Counter>((ref) => CounterNotifier(counter: const Counter(count: 2)));

  await tester.pumpWidget(isEvenTestWidget(mockCounterProvider));

  expect(find.byType(IsEvenMessage), findsOneWidget);
});

In the test, we create a mockProvider with predefined values that we need for testing ScreenHome() widget rendering. In this example, our provider is initialized with the state count: 2.

We are testing that the isEvenMessage() widget is rendered with an even count (of 2). Another test tests that the widget is not rendered with an odd count.

StateNotifier Constructor

class CounterNotifier extends StateNotifier<Counter> {
  CounterNotifier({Counter counter = const Counter(count: 0)}) : super(counter);

  void increment() {
    state = state.copyWith(count: state.count + 1);
  }
}

In order to be able to create a mockProvider with a predefined state, it is important that the StateNotifier (counter_state.dart) constructor includes an optional parameter of the state model. The default argument is how the state should normally initialize. Our tests can optionally provide a specified state for testing which is passed to super().


Build Runner

Code generator is required for freezed class code generation

$ flutter pub run build_runner build --delete-conflicting-outputs
You might also like...

Managing flutter navigation with riverpod.

Navigation for Riverpod Managing Flutter navigation with riverpod. Usage Bootstrap Replace your root ProviderScope with a RiverpodNavigation widget wi

Sep 5, 2022

Implementing Firebase Authentication with Riverpod following Flutter Domain Driven Development pattern

firebase_auth_flutter_ddd Firebase authentication example with Hooks Riverpod and Freezed following Flutter DDD architecture Getting Started This proj

Jan 8, 2023

Todo App with Flutter + CleanArchitecture + sqflite + riverpod + state_norifier + freezed!

Todo App with Flutter + CleanArchitecture + sqflite + riverpod + state_norifier + freezed!

CleanArchitectureTodoAppTrainingWithFlutter Flutter + CleanArchitecture + sqflite + riverpod + state_notifier + freezed! Motivation I wanted to practi

Dec 16, 2022

Some built-in live templates support developers to use Flutter Riverpod faster on Intellij based

Flutter Riverpod live templates Flutter Riverpod live templates is a way to enhance the way you use Riverpod. It contains a collection of different sn

Dec 16, 2022

template with tests, login flow, riverpod, logging ect.

Flutter Template What to accomplish has tests basic auth flow riverpod as state provider logging (sentry) navigation (I used Beamer last time but migh

Dec 22, 2022

Flutter example project to run Solidity smart contracts using web3Dart library

Flutter example project to run Solidity smart contracts using web3Dart library

Fluthereum Description Flutter example project to run Solidity smart contracts using web3Dart library Dependencies web3dart: A dart library that conne

Dec 27, 2022

This is an example project for Firebase integration using flutter.

This is an example project for Firebase integration using flutter.

Flutter Firebase Integration Example Project In this video we have shown how to create #Firebase app from firebase console and integrate that into #Fl

Jul 28, 2022

Example app using Flutter and Firebase

Example app using Flutter and Firebase

Flutter Example App Example app with Flutter that uses Firebase Base project made with much ❤️ . Contains CRUD, patterns, and much more! Report bug ·

Nov 6, 2022

Cloth Shop it's an example using Flutter for Android and iOS.

Cloth Shop it's an example using Flutter for Android and iOS.

Cloth Shop - Flutter Cloth Shop it's an example using Flutter for Android and iOS. About This repository serves the source code for the Ecommers sampl

Oct 4, 2022
Owner
Matthew Rideout
Currently specializing in Firebase, Node.js, React, and Flutter.
Matthew Rideout
A sample flutter app with mock API for movie details

movie_app A new Flutter project. screenshots Getting Started This project is a starting point for a Flutter application. A few resources to get you st

null 2 Oct 25, 2022
A mock library for Dart inspired by mockito

?? mocktail This repository contains mocking libraries for Dart inspired by mockito. package:mocktail A Dart mocking library which simplifies mocking

Felix Angelov 430 Dec 25, 2022
Caching with flutter riverpod and looking into future providers. Example to demonstrate stale while revalidate pattern.

FLUTTER SWR EXAMPLE Test stale-while-revalidate pattern with riverpod. Look; query_provider package Backend calls are made with ghibli-api Tested Prov

Dipesh Dulal 7 Jun 30, 2022
Shopping app with riverpod state management

Shopify Shopify admin rest api demo project. We are try to use riverpod as state management to improve widget rebuilding performance. May be at some p

null 35 Nov 19, 2022
Weather App built in Flutter and Riverpod state management

?? Weather App built with Riverpod This is a weather app built using Riverpod as it's State Management. This project is an attempt to rewrite the Weat

Temitope Ajiboye 49 Dec 7, 2022
A playground for me to learn the Riverpod state management library in Flutter.

clothes_shop A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if

Benhenneda Majid 2 Oct 25, 2021
A flutter todo/task listing example app with advance state management using `Momentum` library.

A flutter todo/task listing example app with advanced state management using Momentum library. Simple on the outside but powerful in the inside. This

xamantra 17 Oct 11, 2022
A basic implementation of the robot testing pattern for integration/e2e tests

robot A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this is

Samuel Abada 3 Dec 13, 2021
Rest API Movie Application built using Flutter and Riverpod

Flickd Flutter Application Flickd Movie Application Flutter Flutter allows you to build beautiful native apps on iOS and Android Platforms from a sing

null 20 Dec 5, 2022
A new practical project made with Flutter and some native widgets, movie API, provider state and more.

Flutter Movie App This project was created with Flutter and some native Widgets like SingleChildScrollView, Hero Animation, SliverAppBar, StreamBuilde

Paúl 4 Jul 12, 2022