异步代码的 UnitTest 示例

Jas*_*per 5 dart dart-unittest dart-async

某种方式阅读了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
Run Code Online (Sandbox Code Playgroud)

}); }

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

Future AddMessage(String message);
Run Code Online (Sandbox Code Playgroud)

并返回completer.future

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

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

你能写一个小代码示例来回答如何测试返回的函数Future吗?在测试中,我的意思是 - 有时我想测试返回(成功时)值,如果成功值不正确并且另一个测试应该失败则测试失败,然后函数将失败Future并进入onError:阻止。

Jun*_*ont 5

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

我相信你使用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 !');
  }
);
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

或测试异常:

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

如果你想检查完成的值,你可以这样做:

expect(database.AddMessage(null).then((value) {
  expect(value, isNotNull);
}), completes);
Run Code Online (Sandbox Code Playgroud)

看: