2013-04-10 43 views
2

閱讀Unit Testing with Dart之後,我仍然無法理解如何將它與Future s一起使用。異步代碼的單元測試示例

例如:

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爲null,則作爲函數將失敗完成者:.completeError('Message can not be null');

在實際測試中,我想測試是否成功Future或完成時發生錯誤。因此,上述這是我試着去了解如何測試Future回報 - 的問題,這是本次測試不會失敗 :(

你能回答寫一個小代碼示例如何測試返回Future功能和?測試我的意思是 - 有時我想測試成功時的返回值和失敗測試,​​如果成功值不正確,並且另一個測試失敗,則功能將失敗Future並輸入到onError:區塊

回答

3

我剛剛重新閱讀您的問題,我意識到我在回答那種錯誤的問題......

我相信你錯誤地使用expectAsyncexpectAsync用於包裝具有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); 

參見:

+0

在我的補償了'fail'崩潰,出現異常和堆棧跟蹤等試驗......是否有任何其他的方式來明確地'fail'的考驗嗎? – Jasper 2013-04-11 06:38:47

1

一個Future可以從test()方法返回 - 這將導致單元測試等待Future完成。

我通常會將我的expect()調用放在then()回調中。例如:

test('foo',() { 
    return asyncBar().then(() => expect(value, isTrue)); 
});