Cheats testing providers
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 ...
});
}
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()),
)
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(),
),
),
);
- Riverpod providers are stored in the nearest
ProviderContainer, which is created byProviderScope. - Without a
ProviderScope, any call toref.read(...)orConsumerWidgetwill throw errors because there is no provider context.
- Always wrap your widget tree in
ProviderScopein tests (unit, widget, golden) if your code uses Riverpod. - This applies to all widgets that use
ref,ConsumerWidget, orConsumerStatefulWidget.
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
}
}
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(),
),
),
),