使用showDialog函数和'BuildContext'参数进行单元测试void函数

时间:2019-10-10 12:53:39

标签: function unit-testing flutter dart

我正在为showAlertDialog()函数编写单元测试,该函数显示带有短消息和OK按钮的警报对话框。

函数看起来像这样

import 'package:flutter/material.dart';

void showAlertDialog(BuildContext context) {
  Widget okButton = FlatButton(
    child: Text("OK"),
    onPressed: () {
      Navigator.of(context).pop(); // Closes alert
      Navigator.of(context).pop(); // Closes drawer
    },
  );

  AlertDialog alert = AlertDialog(
    title: Text("Success", style: TextStyle(color: Colors.green)),
    content: Text("API key has beed updated succesfully."),
    actions: [
      okButton,
    ],
  );

  showDialog(
    context: context,
    builder: (BuildContext context) => alert,
  );
}

使用Flutter文档,我试图使用testWidget类来检查警报Widget是否像这样正确构建:

main() {
  testWidgets('Show code 200', (WidgetTester tester) async {
    await tester.pumpWidget(Builder(builder: (BuildContext context) {
      return showAlertDialog(context);
    }));
    final titleFinder = find.text('Success');
    final messageFinder = find.text('API key has beed updated succesfully.');
    expect(titleFinder, findsOneWidget);
    expect(messageFinder, findsOneWidget);
  });
}

但是由于error: The return type 'void' isn't a 'Widget', as defined by anonymous closure. (return_of_invalid_type_from_closure at [app] test\alert_dialog_test.dart:8),它无法编译。

当我从showAlertDialog声明中删除void语句时,它将编译,但会因以下错误而崩溃:

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown building Builder(dirty):
No MaterialLocalizations found.
Builder widgets require MaterialLocalizations to be provided by a Localizations widget ancestor.
Localizations are used to generate many different messages, labels,and abbreviations which are used
by the material library.
To introduce a MaterialLocalizations, either use a  MaterialApp at the root of your application to
include them automatically, or add a Localization widget with a MaterialLocalizations delegate.
The specific widget that could not find a MaterialLocalizations ancestor was:
  Builder
The ancestors of this widget were:
  [root]

如何以适当的方式对这个功能进行单元测试?

0 个答案:

没有答案