5

在以某种方式阅读了Dart 单元测试后,我仍然无法理解如何将它与Futures 一起使用。

例如:

void main()
{
    group('database group',(){
    setUp( () {
                // Setup
           });

    tearDown((){
                // TearDown
           });

    test('open connection to local database', (){
        DatabaseBase database = null;

        expect(database = new MongoDatabase("127.0.0.8", "simplechat-db"), isNotNull);

        database.AddMessage(null).then(
            (e) {
                  expectAsync1(e) 
                  {
                     // All ok
                  }
                },
            onError: (err)
                     {
                        expectAsync1(bb)
                        {
                          fail('error !');
                        }
                     }
         );

});

// Add more tests here

}); }

因此,在测试中,我创建了一个基本抽象类的实例,DatabaseBase其中包含一些实际MongoDb类的参数,并立即检查它是否已创建。然后我只运行一些非常简单的函数:AddMessage. 这个函数定义为:

Future AddMessage(String message);

并返回completer.future

如果传递message为空,则该函数将失败完成者:.completeError('Message can not be null');

在实际测试中,我想测试是否Future成功完成或有错误。所以以上是我尝试了解如何测试Future返回 - 问题是这个测试没有失败 :(

您能否在答案中写一个小代码示例如何测试返回的函数Future?在测试中我的意思是-有时我想测试返回(成功时)值,如果成功值不正确,则测试失败,而另一个测试应该失败,那么函数将失败Future并进入onError:阻塞。

4

2 回答 2

4

我刚刚重新阅读了你的问题,我意识到我在回答错误的问题......

我相信你使用expectAsync不正确。expectAsync用于包装带有 N 个参数的回调并确保它运行count时间(默认为 1)。

expectAsync将确保任何异常都被测试本身捕获并返回。它本身实际上并没有任何期望(错误的命名法。)

你想要的只是:

database.AddMessage(null).then(
  (value) { /* Don't do anything! No expectations = success! */ },
  onError: (err) { 
    // It's enough to just fail!
    fail('error !');
  }
);

或者如果您需要确保测试完成到某个特定值:

database.AddMessage(null).then(
  expectAsync1((value) { /* Check the value in here if you want. */ }),
  onError: (err) { 
    // It's enough to just fail!
    fail('error !');
  }
);

另一种方法是使用completes匹配器。

// This will register an asynchronous expectation that will pass if the
// Future completes to a value.
expect(database.AddMessage(null), completes);

或测试异常:

// Likewise, but this will only pass if the Future completes to an exception.
expect(database.AddMessage(null), throws);

如果要检查完成的值,可以执行以下操作:

expect(database.AddMessage(null).then((value) {
  expect(value, isNotNull);
}), completes);

看:

于 2013-04-10T17:51:37.510 回答
3

AFuture可以从test()方法返回 - 这将导致单元测试等待Future完成。

我通常把我的expect()电话放在then()回调中。例如:

test('foo', () {
  return asyncBar().then(() => expect(value, isTrue));
});
于 2015-03-07T09:22:02.040 回答