飞镖单元测试 - 总是通过

时间:2014-09-29 04:25:27

标签: dart dart-async dart-unittest

所有

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

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的值是什么,它总是通过。

帮助表示赞赏。

2 个答案:

答案 0 :(得分:2)

在这种简单的情况下,你可以回归未来。单元测试框架识别它并等待未来完成。这也适用于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));
    });
  });
}

答案 1 :(得分:1)

问题是你的代码返回Future,你的测试在Future的代码完成之前就完成了,所以没有什么可以让它失败。

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

以下是一个示例(请注意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));
  }));
});