1

我正在做一个颤振的网络项目,我有一个小部件我想写测试。这个小部件正在使用MouseRegion当它被用户悬停或不悬停时执行一些操作。

举个例子:


class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  bool isHovered = false;
  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onExit: (_) {
        setState(() {
          isHovered = false;
        });
      },
      onEnter: (_) {
        setState(() {
          isHovered = true;
        });
      },
      child: Container(
        color: isHovered ? Colors.blue : Colors.red,
        height: 50,
        width: 50,
      )
    );
  }
}

我可以编写一个小部件测试来测试我的容器是红色的:

testWidgets('MyWidget should be red by default', (WidgetTester tester) async {
  await tester.pumpWidget(
    MyWidget(),
  );
  expect(find.byWidgetPredicate((Widget widget) => widget is Container && widget.color == Colors.red), findsOneWidget);
  expect(find.byWidgetPredicate((Widget widget) => widget is Container && widget.color == Colors.blue), findsNothing);
});

但是如何模拟测试小部件中的悬停(以检查容器是否为蓝色)?

4

1 回答 1

6

这是我设法做到的

testWidgets('MyWidget should be red by default', (WidgetTester tester) async {
  await tester.pumpWidget(
    MyWidget(),
  );
  expect(find.byWidgetPredicate((Widget widget) => widget is Container && widget.color == Colors.red), findsOneWidget);
  expect(find.byWidgetPredicate((Widget widget) => widget is Container && widget.color == Colors.blue), findsNothing);

  final gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
  await gesture.addPointer(location: Offset.zero);
  addTearDown(gesture.removePointer);
  await tester.pump();
  await gesture.moveTo(tester.getCenter(find.byType(MyWidget)));
  await tester.pumpAndSettle();

  expect(find.byWidgetPredicate((Widget widget) => widget is Container && widget.color == Colors.red), findsNothing);
  expect(find.byWidgetPredicate((Widget widget) => widget is Container && widget.color == Colors.blue), findsOneWidget);
});
于 2021-03-07T11:25:34.447 回答