首页 > 解决方案 > Flutter:导航在应用程序中有效,但在单元测试中无效

问题描述

导航在实际应用程序中适用于我,但不适用于单元测试。

这有效(点击“Go to page2”导航到/page2):

  runApp(
    MaterialApp(
      routes: {
        "/": (BuildContext context) => Scaffold(
          body: Column(
            children: [
              Text("Home"),
              TextButton(
                onPressed: () {
                  print("pressed [Go to page2]");
                  Navigator.pushReplacementNamed(context, "/page2");
                },
                child: Text("Go to page2"),
              )
            ]
          )
        ),
        "/page2": (BuildContext context) => Scaffold(
          body: Text("Page 2")
        ),
      },
    )
  );

但是当我在单元测试中尝试这个确切的代码并假装点击按钮时 - 我确实在控制台中看到消息“按下 [转到第 2 页]”,所以我知道按钮被点击了,但导航本身似乎没有发生是因为在页面上找不到文本“第 2 页”:

  testWidgets("Test", (WidgetTester tester) async {
    await tester.pumpWidget(
      MaterialApp(
        routes: {
          "/": (BuildContext context) => Scaffold(
            body: Column(
              children: [
                Text("Home"),
                TextButton(
                  onPressed: () {
                    print("pressed [Go to page2]");
                    Navigator.pushReplacementNamed(context, "/page2");
                  },
                  child: Text("Go to page2"),
                )
              ]
            )
          ),
          "/page2": (BuildContext context) => Scaffold(
            body: Text("Page 2")
          ),
        },
      )
    );

    expect(find.text("Home"), findsOneWidget); // Passes

    await tester.tap(find.byType(TextButton)); // Correctly prints "pressed [Go to page2]"
    await tester.pump(Duration(seconds: 10));

    expect(find.text("Home"), findsOneWidget); // Passes
    expect(find.text("Page 2"), findsOneWidget); // FAILS!!
  });

我究竟做错了什么?

为什么此代码在实际应用程序中有效,但在单元测试中无效?

标签: flutterflutter-test

解决方案


推荐阅读