I want to override the build method of NotifierProvider during WidgetTest, but I don't know how to do it

61 views Asked by At

This is how GoRouter is managed by NotifierProvider (or more precisely, AutoDisposeNotifierProvider).

import 'package:flutter/widgets.dart';
import 'package:go_router/go_router.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'router_provider.g.dart';

@riverpod
class Router extends _$Router {
  @override
  GoRouter build() => GoRouter(
        routes: <RouteBase>[
          GoRoute(
            path: '/',
            name: 'sprashScreen',
            builder: (context, state) {
              return const SprashScreen();
            },
            routes: <RouteBase>[
              GoRoute(
                path: 'firstScreen',
                name:'firstScreen',
                builder: (context, state) {
                  return const FirstScreen();
                },
              ),
            ],
          ),
        ],
      );

  BuildContext get context =>
      state.configuration.navigatorKey.currentState!.overlay!.context;

  void pop() {
    context.pop(false);
  }
}

And I want to change (override) the path of GoRouter during WidgetTest, but I don't know how. How can I override the build method of NotifierProvider?

1

There are 1 answers

2
Charles On

When mocking generated notifiers, you have to extend the notifier's base class which means you have to define your mock class in the same file of the notifier.

// router_provider.dart
// ignore: prefer_mixin
class MockRouter extends _$Router with Mock implements Router {
  @override
  GoRouter build() => GoRouter(...);
}

// in you test file, override the provider with the mock version
final container = ProviderContainer(
  overrides: [
    routerProvider.overrideWith(() => MockRouter()),
  ]
);