Flutter的小部件测试EasyLocalization能够进行初始化。

4

我尽力使用最简单的测试方法,但当我确保初始化EasyLocalization时,测试永远不会停止。

如果我不确保初始化EasyLocalization,测试将会崩溃,并显示以下错误信息:The following LateError was thrown attaching to the render tree: LateInitializationError: Field '_deviceLocale@1348168148' has not been initialized.

我的代码:

void main() {
  testWidgets('Should login', (WidgetTester tester) async {
    await initAppWidgetTest(tester);
    expect(find.byType(ElevatedButton), findsOneWidget);
  });
}

Future<void> initAppWidgetTest(WidgetTester tester) async {
  TestWidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();
  getIt.registerSingleton<AppRouter>(
    AppRouter(
      checkIfAuthenticated: CheckIfAuthenticated(),
    ),
  );
  await tester.pumpWidget(initApp());
  await tester.pumpAndSettle();
  await tester.pump(const Duration(seconds: 2));
}

Widget initApp() {
  return EasyLocalization(
    supportedLocales: const [Locale('fr', 'FR'), Locale('en', 'EN')],
    path: './assets/languages',
    fallbackLocale: const Locale('fr', 'FR'),
    assetLoader: const CodegenLoader(),
    child: MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => CompanyInfosProvider(),
        ),
        ChangeNotifierProvider(
          create: (_) => SitesInfosProvider(),
        ),
      ],
      child: MyApp(),
    ),
  );
}

1
似乎这个错误是由于在初始化之前访问了一个“late”变量所致。你的代码中有“late”变量吗? - l -_- l
当我运行我的应用程序时,即使我进行集成测试并使用相同的代码,我也没有遇到此问题。我认为这个错误是由于EasyLocalization没有很好地初始化而触发的,但为什么呢? - TheSmartMonkey
1个回答

0

我只是缺少这一行需要在之前完成

WidgetsFlutterBinding.ensureInitialized();

我的理解是,EasyLocalization没有在TestWidgetsFlutterBinding中运行,需要一个真实的应用程序初始化。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接