如何在测试运行程序完成之前测试返回Future的方法?我有一个问题,我的单元测试运行程序在异步方法完成之前就完成了.

推荐答案

下面是如何使用completion匹配器进行测试的完整示例.

import 'package:unittest/unittest.dart';

class Compute {
  Future<Map> sumIt(List<int> data) {
    Completer completer = new Completer();
    int sum = 0;
    data.forEach((i) => sum += i);
    completer.complete({"value" : sum});
    return completer.future;
  }
}

void main() {
  test("testing a future", () {
    Compute compute = new Compute();    
    Future<Map> future = compute.sumIt([1, 2, 3]);
    expect(future, completion(equals({"value" : 6})));
  });
}

在此代码完成之前,单元测试运行器可能无法完成.因此,单元测试似乎执行正确.对于Future,这可能需要更长的时间来完成,正确的方法是使用单元测试包中提供的completion匹配器.

/**
 * Matches a [Future] that completes succesfully with a value that matches
 * [matcher]. Note that this creates an asynchronous expectation. The call to
 * `expect()` that includes this will return immediately and execution will
 * continue. Later, when the future completes, the actual expectation will run.
 *
 * To test that a Future completes with an exception, you can use [throws] and
 * [throwsA].
 */
Matcher completion(matcher) => new _Completes(wrapMatcher(matcher));

人们会忍不住做以下事情,这将是在DART中对返回的future 进行单元测试的不正确方式.警告:以下是测试期货的错误方式.

import 'package:unittest/unittest.dart';

class Compute {
  Future<Map> sumIt(List<int> data) {
    Completer completer = new Completer();
    int sum = 0;
    data.forEach((i) => sum+=i);
    completer.complete({"value":sum});
    return completer.future;
  }
}

void main() {
  test("testing a future", () {
    Compute compute = new Compute();
    compute.sumIt([1, 2, 3]).then((Map m) {
      Expect.equals(true, m.containsKey("value"));
      Expect.equals(6, m["value"]);
    });
  });
}

Dart相关问答推荐

我们应该将多少代码放入构造函数中?

S,返回Future.sync()的函数和不需要等待的异步函数有什么区别?

有没有办法否定IF条件中的模式大小写匹配?

如何在流侦听器中对异步函数调用进行单元测试

构造函数:将预处理的参数存储在传递给最终字段的辅助变量中

如何在 Flutter 包/插件开发中添加assets?

Flutter 如何移动文件

我如何在屏幕上弹出特定的Flutter

dart的Completer和Future?

polymer SEO 是否友好?

如何创建类型别名

您可以将命名参数与简写构造函数参数结合起来吗?

Dart:你如何让 Future 等待 Stream?

如何提高数据与二进制数据转换的 Dart 性能?

pub 依赖和 dev_dependencies 有什么区别?

从 Dart Map 中删除选定的键

如何从 Dart 中的字符串中删除换行符?

有没有办法在 Dart 中通过引用传递原始参数?

在 Dart 中获取集合/列表中数字总和的最简洁方法是什么?

何时在 Dart 中使用 part/part of 与 import/export?