我正在为我的小部件编写一些Flutter 测试,有很多似乎不必要的代码,但我不知道如何在没有它的情况下运行测试.
我需要测试自定义小部件的状态.我有一个现有的GlobalKey
来执行此操作;因此,我需要使用testWidgets
而不是test
进行测试.
以下是我第一次try 的内容:
await tester.pumpWidget(
MyTextField(
key: myFieldKey,
),
);
这导致了以下错误:
No Material widget found. TextField widgets require a Material widget ancestor within the closest LookupBoundary. In Material Design, most widgets are conceptually "printed" on a sheet of material. In Flutter's material library, that material is represented by the Material widget. It is the Material widget that renders ink splashes, for instance. Because of this, many material library widgets require that there be a Material widget in the tree above them. To introduce a Material widget, you can either directly include one, or use a widget that contains Material itself, such as a Card, Dialog, Drawer, or Scaffold.
我加了一个Scaffold
:
await tester.pumpWidget(
Scaffold(
body: MyTextField(
key: myFieldKey,
),
),
);
这给了我这个错误:
No Directionality widget found. Scaffold widgets require a Directionality widget ancestor. ... Typically, the Directionality widget is introduced by the MaterialApp or WidgetsApp widget at the top of your application widget tree...
所以,我加了一个MaterialApp
:
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: MyTextField(
key: myFieldKey,
),
),
),
);
这招奏效了!问题是,我基本上每次测试都要构建一个新的应用程序.我正在编写几十个测试,所有这些测试都需要像这样进行泵送;这会导致大量额外的代码,而且似乎效率很低.有什么办法可以让我的第一次try 奏效吗?这似乎是最简单、最直观的.