【问题标题】:Dart Unit Test - Always passingDart 单元测试 - 始终通过
【发布时间】:2014-09-29 04:25:26
【问题描述】:

全部,

这是一个检查集合大小的单元测试

main() {
  test("Resource Manager Image Load", () {
    ResourceManager rm = new ResourceManager();
    int WRONG_SIZE = 1000000;

    rm.loadImageManifest("data/rm/test_images.yaml").then((_){
      print("Length="+ rm.images.length.toString()); // PRINTS '6' - WHICH IS CORRECT
      expect(rm.images, hasLength(WRONG_SIZE));
    });
  });
}

我从浏览器运行它(客户端 Dart 库正在使用中)并且它总是通过,无论 WRONG_SIZE 的值是多少。

帮助表示赞赏。

【问题讨论】:

    标签: dart dart-async dart-unittest


    【解决方案1】:

    在这种简单的情况下,您可以只返回未来。单元测试框架识别它并等待未来完成。这也适用于setUp/tearDown

    main() {
      test("Resource Manager Image Load", () {
        ResourceManager rm = new ResourceManager();
        int WRONG_SIZE = 1000000;
    
        return rm.loadImageManifest("data/rm/test_images.yaml").then((_) {
        //^^^^
          print("Length="+ rm.images.length.toString()); // PRINTS '6' - WHICH IS CORRECT
          expect(rm.images, hasLength(WRONG_SIZE));
        });
      });
    }
    

    【讨论】:

    • 没意识到;好多了!
    • 我就是这么做的——除了我没有使用'return rm....'。现在它的工作。谢谢。我确实发现 Dart 的这种“到处异步”方法需要一些时间来适应......
    • 是的,很好。你做了什么?
    • 完全按照你的功能......只是没有'return'语句;-)
    • 看来我误解了你的评论;-)。是的 - 只是缺少回报。
    【解决方案2】:

    问题是您的代码返回Future,并且您的测试在Future 中的代码完成之前完成,所以没有什么会导致它失败。

    查看 Dart 网站上的 Asynchronous Tests 部分。像expectAsync 这样的方法允许将future 传递给测试框架,以便它可以等待它们完成并正确处理结果。

    这是一个示例(注意 expect 调用现在在传递给 expectAsync 的函数内)

    test('callback is executed once', () {
      // wrap the callback of an asynchronous call with [expectAsync] if
      // the callback takes 0 arguments...
      var timer = Timer.run(expectAsync(() {
        int x = 2 + 3;
        expect(x, equals(5));
      }));
    });
    

    【讨论】:

      猜你喜欢
      • 2022-11-26
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      相关资源
      最近更新 更多