2

我正在尝试测试我拥有的自定义小部件的回调,它实际上是一个简单的保存图标按钮,但测试失败,因为小部件没有检测到点击。考试:

testWidgets(
  'Save icon callback',
  (WidgetTester tester) async {
    Completer completer = Completer<void>();

    await tester.pumpWidget(
      _TestingApp(
        child: SaveIcon(
          onTap: (_) => completer.complete(),
          initialSaved: false,
        ),
      ),
    );

    var finder = find.byType(InkWell);
    expect(finder, findsOneWidget);

    await tester.tap(finder);

    expect(completer.isCompleted, true);
  },
);

小部件代码:

class SaveIcon extends StatefulWidget {
  SaveIcon({
    @required this.onTap,
    @required this.initialSaved,
  });
  final Function(bool) onTap;
  final bool initialSaved;

  @override
  _SaveIconState createState() => _SaveIconState();
}

class _SaveIconState extends State<SaveIcon> {
  bool _isSaved;

  @override
  void initState() {
    super.initState();
    _isSaved = widget.initialSaved;
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      focusColor: Colors.transparent,
      highlightColor: Colors.transparent,
      splashColor: Colors.transparent,
      onTap: () {
        setState(() {
          _isSaved = !_isSaved;
          widget.onTap(_isSaved);
        });
      },
      child: RotatedBox(
        quarterTurns: 2,
        child: AnimatedSwitcher(
          transitionBuilder: (child, animation) =>
              ScaleTransition(child: child, scale: animation),
          duration: Duration(milliseconds: 250),
          child: _isSaved
              ? Image.asset(
                  'assets/icons/save_filled.png',
                  key: const ValueKey<int>(0),
                  height: 21,
                  color: Colors.white,
                )
              : Image.asset(
                  'assets/icons/save.png',
                  key: const ValueKey<int>(1),
                  height: 21,
                  color: Colors.white,
                ),
        ),
      ),
    );
  }
}

它只是失败,因为完成者没有完成。(错误消息:在运行测试时抛出了以下 TestFailure 对象:预期:true 实际:false)

知道为什么会这样吗?

4

0 回答 0