【问题标题】:How to test the dynamic color of a Widget using testWidgets如何使用 testWidgets 测试 Widget 的动态颜色
【发布时间】:2019-11-27 20:42:01
【问题描述】:

我想为自定义小部件编写单元测试,特别检查基于BuildContext 主题的嵌套Text 小部件的颜色。如何根据BuildContext测试不同的样式?

要测试的小部件:

class ThemedText extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final TextStyle inheritedTextStyle = Theme.of(context).textTheme.subtitle;
    Color customColor = inheritedTextStyle.color;
    if (inheritedTextStyle.color == Colors.blue) {
      customColor = Colors.red;
    }

    return Text(
      'Themed',
      style: inheritedTextStyle.copyWith(color: customColor),
    );
  }
} 

我想写两个测试:

  • 为继承的TextStyle 提供颜色Colors.blue,并测试Text 小部件是否使用覆盖的颜色(即Colors.blue)呈现。
  • 为继承的TextStyle 提供不是Colors.blue 的颜色(例如Colors.green),并测试Text 小部件是否以继承的颜色呈现(例如Colors.green)。

【问题讨论】:

    标签: testing flutter widget themes


    【解决方案1】:

    这样的东西对我有用:

    final textColorFinder = tester.widget<Text>(find.byType(Text));
    
    expect(textColorFinder.style.color, Colors.red);
    

    【讨论】:

      猜你喜欢
      • 2020-11-17
      • 2021-06-29
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-02
      相关资源
      最近更新 更多