【问题标题】:Dart / Flutter Web: How to write a test that covers `kIsWeb == true`?Dart / Flutter Web:如何编写涵盖 `kIsWeb == true` 的测试?
【发布时间】:2023-04-04 22:11:01
【问题描述】:

我想运行一个涵盖两种可能情况的单元测试,包括 Web 和非 Web 部署。要测试的类的代码基本上是这样的:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    if (kIsWeb) {
      return Text("I'm web");
    } else {
      return Text("I'm not web");
    }
  }
}

kIsWeb 是 Dart 提供的常量,用于确定应用程序是否编译为在 Web 上运行。

我当前的测试类实现只能测试非网络路径。有没有办法为kIsWeb == true的情况创建一个测试?

【问题讨论】:

    标签: unit-testing flutter testing dart flutter-web


    【解决方案1】:

    尝试像这样运行测试:

    flutter 测试 --platform chrome

    很遗憾,此方法可能不适用于某些平台(issue 适用于 Windows 10)。 Flutter 网页版仍处于测试阶段。

    更多信息请见here

    【讨论】:

    • 谢谢您,这实际上以有限的方式起作用,因为我必须事先决定要测试哪个平台并且不能同时运行所有测试。此外,不幸的是,选项--platform chrome 不能与我最感兴趣的选项--coverage 一起使用。看到这个GitHub Issue
    【解决方案2】:

    您还可以为您的小部件添加一个构造函数和属性,您将使用@visibleForTesting 进行装饰。类似于:

    class MyWidget extends StatelessWidget {
      final bool isTestingForWeb;
      MyWidget({@visibleForTesting this.isTestingForWeb = false});
    
      @override
      Widget build(BuildContext context) {
        if (kIsWeb || isTestingForWeb) {
          return Text("I'm web");
        } else {
          return Text("I'm not web");
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-14
      • 2018-01-04
      • 2022-07-04
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      相关资源
      最近更新 更多