簡體   English   中英

如何期望在 flutter 小部件測試中拋出異常?

[英]How to expect that an exception is thrown in flutter widgets test?

我有這個測試:

testWidgets('Controller must only be used with one widget at a time',
    (WidgetTester tester) async {
  final CustomAnimatedWidgetController controller = CustomAnimatedWidgetController();

  await tester.pumpWidget(
    MaterialApp(
      home: Scaffold(
        body: Column(
          children: [
            CustomAnimatedWidget(
              child: Container(),
              controller: controller,
            ),
            CustomAnimatedWidget(// this declaration will throw an exception from initState of this widget
              child: Container(),
              controller: controller,
            ),
          ],
        ),
      ),
    ),
  );

  expect(tester.takeException(), isInstanceOf<Exception>());
});

這保證會拋出 Exception 類型的Exception (由於兩次使用 controller),但expect不會捕獲異常。 相反,測試失敗了,我看到控制台中拋出了我的異常。

但是這里這里他們說這是必須使用的方式。 測試有什么問題?

這篇帖子的回答顯示了測試人員要執行的操作(模擬點擊)會導致異常。 我們可以使用expect(tester.takeException(), isInstanceOf<AnExceptionClass>()); 以確保已按預期拋出異常。

在您的情況下,無法正確呈現小部件。 小部件測試應該首先使用正確實現的小部件來完成。

進一步查看pumpWidget的代碼,我們看到它返回TestAsyncUtils.guard<void>(...)所以測試在它自己的“區域”中運行,這就是異常被框架吞沒的原因(甚至添加 try catch上面的pumpWidget周圍沒有發現錯誤)

我找到的唯一方法是覆蓋FlutteError.onError function:

FlutterError.onError = (details){
// handle error here
      };

現在測試可以通過,測試期間拋出的錯誤將轉發給此方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM