繁体   English   中英

编写使用 GoogleFonts 的 flutter 小部件测试

[英]Write flutter widget tests that uses GoogleFonts

我需要编写一个 flutter 小部件测试来测试使用 GoogleFonts 插件的小部件。 但是,它给出了正确的网络故障,因为测试套装无法访问互联网。 问题是 GoogleFonts.majorMonoDisplayTextTheme 是一种 static 方法,这使得在小部件测试中使用时无法模拟 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);
});

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

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

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

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

在此处输入图像描述 首先,您必须在 pubspec.yaml 文件中提供字体只需按照这些步骤下载堡垒提取它。 Go 到您的项目文件并创建一个名为“assets”的文件夹,并在 assets 文件夹中创建另一个名为“fonts”的文件夹。 在这个 fonts 文件夹中粘贴 font.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',
                  ),
                )
              ],
            ),

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM