[英]Dart, how to unit test with zones?
我想測試一條通過多個異步Stream
發送事件的路徑,而我想測試的是,通過Stream
發出無效的參數,我會在最后拋出特定類型的錯誤,但我不確定如何執行此操作,但是查看了區域后,它們似乎提供了一些希望, 這是我失敗的測試,僅運行test/unit/start.dart
文件即可運行test/unit/start.dart
。 奇怪的是,在Zone
中運行的復雜異步路徑確實會引發預期的錯誤類型,因此應該通過。 為了測試這一點,我嘗試將測試更改為一個簡單得多的版本,如果您在失敗的測試中復制以下代碼中的粘貼,則此版本通過:
test('A Source may not have #emitEvent invoked on it', (){
var error;
expectAsyncWithReadyCheckAndTimeout(
() => error != null,
(){
expect(error == 'hi', equals(true));
});
runZoned(
(){
executeWhenReadyOrTimeout(() => currentTestConsumer != null, (){ new Future((){}).then((_){ throw 'hi'; });});
},
onError: (e){
error = e;
});
});
我無法弄清楚為什么正確的版本無法通過區域onError處理程序捕獲其錯誤,以及簡化的版本為什么起作用。
解決此問題的關鍵是要了解錯誤的出處,而並不是最終導致引發錯誤的復雜異步路徑在我的單元測試區域中就已經開始了,但事實並非如此。都創造了領先的測試設置方法的時間,使像對象 / 流 / 期貨 /等復雜的異步通路的組成部分,這似乎特別關心的流 。 進行這項工作的關鍵是在runZoned主體內的setUp方法中運行語句並從那里處理錯誤,或者,我可以使setUp方法在每次單元測試開始時被明確調用,以便我可以顯式調用runZoned體內的整個setUp方法。
無論哪種方式,作為我如何使其正常工作的代碼示例,它可能都是最說明性的示例,它顯示了我用來弄清為什么它不起作用的實驗代碼,盡管這實際上正是我的庫測試代碼中正在發生的事情:
import 'dart:async';
import 'package:unittest/unittest.dart';
void main(){
test('This will fail', (){
var error;
Timer.run(expectAsync((){
expect(error, equals('anError'));
}));
//create the stream and controller outside the zone
var controller = new StreamController<String>();
var stream = controller.stream.asBroadcastStream();
stream.listen((_){ throw 'anError'; });
runZoned((){
//kick off the async pathway to throw the error
controller.add('');
}, onError: (e){
error = e;
});
});
test('This will pass', (){
var error;
Timer.run(expectAsync((){
expect(error, equals('anError'));
}));
runZoned((){
//create the stream and controller inside the zone
var controller = new StreamController<String>();
var stream = controller.stream.asBroadcastStream();
stream.listen((_){ throw 'anError'; });
//kick off the async pathway to throw the error
controller.add('');
}, onError: (e){
error = e;
});
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.