[英]How to write Flutter widget test for a widget that uses the Connectivity plugin
[英]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.