如何使用 testWidgets 测试 Widget 的动态颜色

Tho*_*mas 6 testing themes widget flutter

我想为自定义小部件编写单元测试,特别是检查Text基于BuildContext. 我如何基于 测试不同的样式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),
    );
  }
} 
Run Code Online (Sandbox Code Playgroud)

我想写两个测试:

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

Cod*_*red 0

这样的事情对我有用:

final textColorFinder = tester.widget<Text>(find.byType(Text));

expect(textColorFinder.style.color, Colors.red);
Run Code Online (Sandbox Code Playgroud)