编写使用 Google 字体的 flutter widget 测试

Write flutter widget tests that uses GoogleFonts

我需要编写一个 flutter 小部件测试来测试使用了 GoogleFonts 插件的小部件。但是,它给出了正确的网络故障,因为测试服无法访问互联网。问题是 GoogleFonts.majorMonoDisplayTextTheme 是一个静态方法,这使得在小部件测试中使用时无法模拟 GoogleFont class。

Error: google_fonts was unable to load font MajorMonoDisplay-Regular because the following exception occurred: 
Exception: Failed to load font with URL: https://fonts.gstatic.com/s/a/9901077f5681d4ec7e01e0ebe4bd61ba47669c64a7aedea472cd94fe1175751b.ttf

小工具使用:

 Container(
      padding: EdgeInsets.only(top: 10),
      child: Text(
        _now,
        style: GoogleFonts.majorMonoDisplayTextTheme(Theme.of(context).textTheme).headline3,
      ),
    ),

小部件测试方法:

testWidgets(
  'Shoudl display _now text',
  (WidgetTester tester) async {
  await tester.pumpWidget(_TestWidgetWithGoogleFont);
  await tester.pumpAndSettle();
  expect(find.byType(Text), findsOneWidget);
});

首先你必须在pubspec.yaml文件中提供字体 只需按照这些步骤 下载堡垒解压它。 转到您的项目文件并创建一个名为“assets”的文件夹,并在 assets 文件夹中创建另一个名为“fonts”的文件夹。在此字体文件夹中粘贴字体 .tiff 复制文件名,在本例中为“MajorMonoDisplay-Regular.ttf”

接下来您必须在 pubspec.yaml 文件中提供字体信息 只需复制粘贴这些代码即可。

  fonts:
- family: MajorMonoDisplay
  fonts:
    - asset: assets/fonts/MajorMonoDisplay-Regular.ttf

下一步打开终端运行“flutter pub get” 现在只需在您的 TextStyle 中提供堡垒系列。 示例:

child: Column(
              children: [
                Text(
                  'Should display _now text',
                  style: TextStyle(
                    fontSize: 20,
                    fontFamily: 'MajorMonoDisplay',
                  ),
                )
              ],
            ),

如果前面没有显示,请关闭应用程序并重新运行。

还有另一种消除错误的方法。如果您不想(或不能)向项目添加其他文件,则特别方便。

只需将这行代码添加到所需的测试中即可:

setUp(() => GoogleFonts.config.allowRuntimeFetching = false);

此代码不允许运行时提取,这是一个首先引发错误的过程。