简体   繁体   English

如何编写小部件树测试以验证树层次结构

[英]How to write widget tree test to verify tree hierarchy

I am learning Flutter and I want to write one test for my simple MyAppBarWidget .我正在学习 Flutter ,我想为我的简单MyAppBarWidget编写一个测试。 Below is my widget下面是我的小部件

class MyAppBarWidget extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: Text("My first widget"),
          ),
        ));
  }
}

I want to test widget tree hierarchy as我想将小部件树层次结构测试为

  • MaterialApp has Scaffold property MaterialApp 具有 Scaffold 属性
  • Scaffold has AppBar property Scaffold 有 AppBar 属性
  • AppBar has title property as Text AppBar 的 title 属性为 Text
  • title is My first widget标题是我的第一个小部件

Any suggestion what kind of test I should write任何建议我应该写什么样的测试

I tried below test我试过下面的测试

void main() {
  testWidgets("verify app bar", (WidgetTester tester) async {
    await tester.pumpWidget(MyAppBarWidget());
    var byWidget = find.byType(MaterialApp);
    var text = find.text("My first widget");
    expect(byWidget, findsOneWidget);
    expect(text, findsOneWidget);
  });
}

But this test does not say that my text field is inside AppBar widget但是这个测试并没有说我的文本字段在 AppBar 小部件内

Can someone help me how should I write test to verify this?有人可以帮助我如何编写测试来验证这一点吗?

Thanks谢谢

I suggest not to test widget hierarchy, you will change it often and always have to adjust the test without actually knowing anything when the test fails or succeeds.我建议不要测试小部件层次结构,您会经常更改它并且总是必须在测试失败或成功时实际上不知道任何事情的情况下调整测试。 It is better to test functionality, the presence of something or the absence, tap events and interaction.最好测试功能、某物的存在或不存在、点击事件和交互。

You can also look into golden (screenshot) tests to ensure that screens or pages don't change.您还可以查看黄金(屏幕截图)测试以确保屏幕或页面不会更改。

That being said, if you really want to do this you can use话虽这么说,如果你真的想这样做,你可以使用

find.ancestor(find.byType(AppBar), find.text("My first widget"));

EDIT编辑

Or with newer versions of the test library, thanks Fred Grott :或者使用更新版本的测试库,感谢Fred Grott

find.ancestor(of: find.byType(AppBar), matching: find.text("My first widget"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM