Widget测试Mock GoRouter时遇“No GoRouter found in context”错误求助
解决go_router 6.0.0测试中Mock路由失败的问题
问题根源
你的测试代码直接使用内部类InheritedGoRouter传递Mock路由实例,但在go_router 6.0.0版本中,context.pushNamed扩展方法依赖的路由实例需要通过官方标准的MaterialApp.router配置注入,直接嵌套InheritedGoRouter无法让子widget的context正确获取到路由实例,从而抛出No GoRouter found in context错误。
修正后的测试代码
- 先确保Mock类正确实现
GoRouter接口(基于mockito):
class MockGoRouter extends Mock implements GoRouter {}
- 修改测试的Widget包裹逻辑,用
MaterialApp.router替代普通MaterialApp:
final router = MockGoRouter(); // 匹配带参数的pushNamed调用,覆盖业务中的参数传递场景 when(router.pushNamed( any, queryParams: anyNamed('queryParams'), )).thenReturn(null); await tester.pumpWidget( MultiProvider( providers: [ BlocProvider<ProfileBloc>(create: (context) => profileBloc), ], child: MaterialApp.router( locale: const Locale("en"), routerConfig: router, // 直接注入Mock路由实例 builder: (context, child) => ProfileEditWidget(), ), ), ); await tester.pump(); await tester.tap(find.byKey(const Key('btnSubmit'))); await tester.pumpAndSettle(); // 确保路由跳转相关的帧处理完成
额外验证技巧
如果需要确认路由跳转的参数是否符合预期,可以在测试末尾添加断言:
verify(router.pushNamed( VERIFY_PHONE, queryParams: {'updatedPhone': '你的测试手机号'}, )).called(1);
注意:避免直接使用go_router的内部类(如InheritedGoRouter),这类API不属于对外暴露的稳定接口,版本迭代中可能随时变更。
内容的提问来源于stack exchange,提问作者chinloyal
相关产品推荐
相关产品推荐

