This is about how to Mock Riverpod's Notifier and set its status

82 views Asked by At

This is how it is described in the official documentation.

class MyNotifier extends Notifier<int> {
  @override
  int build() => throw UnimplementedError();
}

// Your mock needs to subclass the Notifier base-class corresponding
// to whatever your notifier uses
class MyNotifierMock extends Notifier<int> with Mock implements MyNotifier {}

But I don't know how to use this. How can I set the status?

2

There are 2 answers

0
shark On

Maybe you can use Mock Notifier like this:

MyNotifier's state is int type state,

you can use Mock Notifier when you write test code about your riverPod Notifier codes,

please ref under these codes:

class MyNotifier extends Notifier<int> {
  @override
  int build() {
    return 0;
  }

  void increment() {
    state = state + 1;
  }
}

class MyNotifierMock extends Notifier<int> with Mock implements MyNotifier {
  @override
  int build() {
    return 0;
  }

  void increment() {
    state = state + 2;
  }
}
0
LBeyers On

per the official docs

It is generally discouraged to mock Notifiers. 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" that the Notifier uses to fetch data from.

The docs provide examples:

@riverpod
class MyNotifier extends _$MyNotifier {
  @override
  int build() => 123;
}
class MyNotifierMock with Mock implements MyNotifier {}

How can I set the status?

To set the initial state, you can override the Notifier's build, eg:

class MyNotifierMock with Mock implements MyNotifier {
final T? initialState;
const MyNotifierMock(this.initialState);
@override
      int build() => initialState ?? <SomeDefaultValue>;
}