MockClient 需要 1 个位置参数,但找到 0 个

问题描述 投票:0回答:3

我正在尝试使用 Mockito 为 flutter 应用程序创建一些测试。

这是我的代码:

@GenerateMocks([http.Client])
main() {
  group('sendUrlPost', () {
    test('returns alias and links if the post call is successful', () async {
      final client = MockClient();
      String apiUrl = "someApiURL";
      String longUrl = "someUrl";
      when(client.post(Uri.parse(apiUrl),
          headers: {'Content-Type': 'application/json'},
          body: jsonEncode(
              {"url": longUrl}))).thenAnswer((_) async => http.Response(
          '{"alias":"70492","_links":{"self":"https://www.youtube.com","short":"https://url-shortener-nu.herokuapp.com/short/70492"}}',
          200));
      expect(await UrlPostConnector.sendUrlPost(longUrl), isA<UrlResponse>());
    });
  });
}

我完全按照官方指南进行操作: https://docs.flutter.dev/cookbook/testing/unit/mocking 但是当我创建模拟客户端时,我收到以下错误:

最终客户端 = MockClient();

预期有 1 个位置参数,但找到了 0 个。尝试添加 缺少参数

我猜该指南已经过时了,但我还没有找到让它发挥作用的方法。如果您能告诉我我做错了什么以及是否有更好的方法来测试 Http 请求,我将不胜感激。

谢谢

flutter testing mockito httprequest
3个回答
0
投票

我缺少通过运行创建的生成的mocks.dart 文件

 flutter pub run build_runner build

感谢@jamesdlin 指出了这一点。


0
投票

您必须将版本降低到

5.0.0

mockito: ^5.0.0

确保在创建测试类后运行此命令

flutter pub run build_runner build

0
投票

首先确保您添加了注释来生成模拟 导入'包:mockito/annotations.dart';

然后@GenerateMocks([http.Client])

在终端中:dart run build_runner build

导入生成的文件unit_test.mocks.dart

您的本地 unit_test.mocks.dart 文件与 package:http 包中存在的 MockClient 类之间可能存在冲突。

由于这两个文件都有同名的类,Dart 会很困惑该使用哪一个。

解决方案:

将本地 MockClient 类重命名为唯一的名称,例如 MyMockClient。 更新您的代码以使用新命名的类(例如,final MyMockClient client = MyMockClient();)。

希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.