我只是想模仿Flutter 中对小部件测试的介绍,但在我实现的基本代码示例中不断看到测试失败。
这是测试:
void main() {
testWidgets(
"OrderDetailsItemWidget - all fields are provided (quantity, name, and subtext)",
(WidgetTester tester) async {
// Arrange, Act
await tester.pumpWidget(
const OrderDetailsItemWidget(
1,
"name",
"subtext",
),
);
// Assert
expect(
find.byKey(const Key("order_details_item_widget_quantity")),
findsOneWidget,
);
expect(
find.byKey(const Key("order_details_item_widget_name")),
findsOneWidget,
);
expect(
find.byKey(const Key("order_details_item_widget_subtext")),
findsOneWidget,
);
},
);
}
这是OrderDetailsItemWidget
要测试的:
class OrderDetailsItemWidget extends StatelessWidget {
final int _quantity;
final String _name;
final String _subtext;
const OrderDetailsItemWidget(
this._quantity,
this._name,
this._subtext, {
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
const double quantitySquareSideValue = 25.0;
return Container(
margin: const EdgeInsets.only(
top: Dimens.sizeXxxs,
bottom: Dimens.sizeXxxs,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: quantitySquareSideValue,
height: quantitySquareSideValue,
decoration: const BoxDecoration(
color: DesignColor.colorNeutral4,
borderRadius: BorderRadius.all(
Radius.circular(2.0),
),
),
child: Center(
child: Text(
"$_quantity",
key: const Key("order_details_item_widget_quantity"),
style: DesignTypography.typographyBody1.copyWith(
color: DesignColor.colorNeutral100,
),
),
),
),
const SizedBox(
width: Dimens.sizeS,
),
Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
height: 5.0,
),
Text(
_name,
key: const Key("order_details_item_widget_name"),
textAlign: TextAlign.left,
style: DesignTypography.typographySubheading2.copyWith(
color: DesignColor.colorNeutral100,
),
),
if (_subtext != null)
Text(
_subtext,
key: const Key("order_details_item_widget_subtext"),
textAlign: TextAlign.left,
style: DesignTypography.typographyCaption.copyWith(
color: DesignColor.colorNeutral70,
),
),
],
),
)
],
),
);
}
}
但是,它一直失败:
我假设我在这里没有做任何特别的事情,它只是一个基本上带有三个Text
s 的小部件。
我所需要的只是验证Texts
在提供字段值时子小部件( )是否可见。我在这里想念什么?!
请注意,我尝试使用find.text("...")
代替键,但效果不佳。