Flutter集成测试中如何Mock服务以替代真实服务?
解决Flutter集成测试中Mock服务替换真实服务的问题
你的核心问题是未在ProviderScope中覆盖对应的Authentication provider,导致App仍使用真实服务实例。以下是修改后的完整代码及关键说明:
@GenerateMocks([Authentication]) void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('Test display error when email and password are empty', (tester) async { final mockAuthentication = MockAuthentication(); when(mockAuthentication.tokenHasExpired()) .thenAnswer((_) async => true); await tester.pumpWidget( ProviderScope( // 关键:添加overrides覆盖真实的Authentication provider overrides: [ // 替换成你项目中实际的Authentication provider变量名 authenticationProvider.overrideWithValue(mockAuthentication), ], child: const MaterialApp(home: MyApp()) ) ); await tester.pumpAndSettle(const Duration(milliseconds: 5000)); await tester.tap(find.byType(ElevatedButton)); await tester.pump(); expect(find.text('Email address is empty'), findsOneWidget); expect(find.text('Password is empty'), findsOneWidget); }); }
关键说明:
- 确认项目中存在对应的
Authenticationprovider,比如类似这样的定义:final authenticationProvider = Provider<Authentication>((ref) { return RealAuthentication(); // 真实的服务实现 }); - 在测试的
ProviderScope的overrides列表中,通过overrideWithValue将真实provider替换为你创建的mockAuthentication实例 - 若使用其他类型provider(如
StateNotifierProvider),需调整覆盖方式:StateNotifierProvider可使用overrideWithProvider传入返回mock实例的providerFutureProvider可使用overrideWithValue传入预定义的AsyncValue
内容的提问来源于stack exchange,提问作者Piface
相关产品推荐
相关产品推荐

