Testing providers

1. Wrap your widget with ProviderScope in your test

For example, in your golden test or widget test:

import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:presentation/screen/about_screen.dart';

void main() {
  testWidgets('AboutScreen golden', (WidgetTester tester) async {
    await tester.pumpWidget(
      ProviderScope(
        child: MaterialApp(
          home: AboutScreen(),
        ),
      ),
    );
    // ... your golden assertions ...
  });
}

2. If you use custom providers or overrides

You can pass overrides to ProviderScope if you want to mock or stub providers:

ProviderScope(
  overrides: [
    authServiceProvider.overrideWithValue(MockAuthService()),
    // ...other overrides...
  ],
  child: MaterialApp(home: AboutScreen()),
)

3. For golden tests using Alchemist or similar frameworks

If you use a golden test runner (like Alchemist), make sure the widget you pass to the golden test is wrapped in a ProviderScope:

goldenTest(
  'AboutScreen golden',
  builder: () => ProviderScope(
    child: MaterialApp(
      home: AboutScreen(),
    ),
  ),
);

Why this is needed

  • Riverpod providers are stored in the nearest ProviderContainer, which is created by ProviderScope.
  • Without a ProviderScope, any call to ref.read(...) or ConsumerWidget will throw errors because there is no provider context.

Summary

  • Always wrap your widget tree in ProviderScope in tests (unit, widget, golden) if your code uses Riverpod.
  • This applies to all widgets that use ref, ConsumerWidget, or ConsumerStatefulWidget.

Example overriding the NetworkServiceProvider


1. Create a fake/mock NetworkServiceNotifier

You can subclass NetworkServiceNotifier and override its state:

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:services/provider/network/network_service_provider.dart';
import 'package:services/provider/network/network_service_state.dart';

class FakeNetworkServiceNotifier extends NetworkServiceNotifier {
  FakeNetworkServiceNotifier()
      : super() {
    // Immediately set state to online
    state = NetworkServiceState(networkStatus: NetworkStatus.online);
  }

  @override
  void _startMonitoring() {
    // Do nothing: disable real monitoring in tests
  }

  @override
  Future<void> _checkNetworkStatus() async {
    // Do nothing: disable real checks in tests
  }
}

2. Override the provider in your golden test

Wrap your widget with a ProviderScope and override the networkServiceProvider:

import 'package:flutter_riverpod/flutter_riverpod.dart';
// ...other imports...

GoldenTestScenario(
  name: 'AboutScreen',
  child: ProviderScope(
    overrides: [
      networkServiceProvider.overrideWith((ref) => FakeNetworkServiceNotifier()),
    ],
    child: wrapWithMaterialApp(
      useFakeBundle: false,
      child: AboutScreen(),
    ),
  ),
),