Skip to content

Commit

Permalink
Document how to use a mocked notifier inside tests (#3367)
Browse files Browse the repository at this point in the history
  • Loading branch information
rrousselGit committed Feb 26, 2024
1 parent 42bfe81 commit 2e27da7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
11 changes: 9 additions & 2 deletions website/docs/essentials/testing.mdx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: Testing your providers
version: 1
version: 2
---

import { AutoSnippet, When } from "/src/components/CodeSnippet";
Expand All @@ -15,6 +15,7 @@ import autoDisposeListen from "!!raw-loader!./testing/auto_dispose_listen.dart";
import listenProvider from "!!raw-loader!./testing/listen_provider.dart";
import awaitFuture from "!!raw-loader!./testing/await_future.dart";
import notifierMock from "./testing/notifier_mock";
import notifierUsage from "!!raw-loader!./testing/notifier_usage.dart";

A core part of the Riverpod API is the ability to test your providers in isolation.

Expand Down Expand Up @@ -135,7 +136,9 @@ One way to do so is to read the `.future` of a provider:

## Mocking Notifiers

It is generally discouraged to mock Notifiers.
It is generally discouraged to mock Notifiers. This is because Notifiers cannot be
instantiated on their own, and only work when used as part of a Provider.

Instead, you should likely introduce a level of abstraction in the logic of your
Notifier, such that you can mock that abstraction.
For instance, rather than mocking a Notifier, you could mock a "repository"
Expand All @@ -161,3 +164,7 @@ For this to work, your mock will have to be placed in the same file as the
Notifier you are mocking. Otherwise you would not have access to the `_$MyNotifier` class.

</When>

Then, to use your notifier you could do:

<AutoSnippet raw={notifierUsage} />
22 changes: 22 additions & 0 deletions website/docs/essentials/testing/notifier_usage.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// ignore_for_file: unused_local_variable

import 'package:flutter_test/flutter_test.dart';

import 'create_container.dart';
import 'notifier_mock/codegen.dart';

/* SNIPPET START */
void main() {
test('Some description', () {
final container = createContainer(
// Override the provider to have it create our mock Notifier.
overrides: [myNotifierProvider.overrideWith(MyNotifierMock.new)],
);

// Then obtain the mocked notifier through the container:
final notifier = container.read(myNotifierProvider.notifier);

// You can then interact with the notifier as you would with the real one:
notifier.state = 42;
});
}

0 comments on commit 2e27da7

Please sign in to comment.