1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

自動テストにてAsyncNotifierProviderのMockを作成する

Posted at

こんなAsyncNotifierProviderがあったとして

code.dart
class UserIdListNotifier extends AsyncNotifier<List<int>> {
  @override
  Future<List<int>> build() async {
    return [1];
  }
}

final UserIdListProvider = AsyncNotifierProvider<UserIdListNotifier, List<int>>(() {
  return UserIdListNotifier();
});

こんなテストコードになります。

test_code.dart
void main() {
    testWidgets('テストします',(WidgetTester tester) async {
        await tester.pumpWidget(
          ProviderScope(
            overrides: [ // ここでProviderの戻り値をMockしたNotifierに設定する
              UserIdListProvider.overrideWith(() {
                return UserIdListNotifierMock();
              }),
            ],
            home: SomeWidget()
          ),
        );
    }
}

class UserIdListNotifierMock // NotifierをMockする
    extends AsyncNotifier<List<int>>
    with Mock
    implements UserIdListNotifier {
  @override
  Future<List<int>> build() async {
    return [1,2,3];
  }
}

参考:https://riverpod.dev/docs/essentials/testing#mocking-notifiers
(非推奨らしいです...)

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?