学写 Flutter 单元测试

你如果跟我一样,看到类似的文档,教你怎么写单元测试,https://github.com/dart-lang/test/blob/master/pkgs/test/README.md

就兴冲冲的把如下代码,往 Flutter 项目里的一贴

import "package:test/test.dart";

void main() {
  test("String.split() splits the string on the delimiter", () {
    var string = "foo,bar,baz";
    expect(string.split(","), equals(["foo", "bar", "baz"]));
  });

  test("String.trim() removes surrounding whitespace", () {
    var string = "  foo ";
    expect(string.trim(), equals("foo"));
  });
}

肯定会报错,说:Error: Could not resolve the package 'test' in 'package:test/test.dart'.

怎么办?

有两种办法解决:

  1. 添加依赖
    打开 Flutter 项目根目录里的 pubspec.yaml,找到 dev_dependencies (新项目大概在27行处),在下面添加 test: ^1.5.1
    在命令行执行:flutter packages get,就能添加这个依赖。

或者

  1. 使用 Flutter 自带的依赖
    import "package:test/test.dart"; 换为 import 'package:flutter_test/flutter_test.dart';

最后,重新运行测试命令:flutter test

    原文作者:Kenny锅
    原文地址: https://www.jianshu.com/p/e25d09e1ed5c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞