小编Mer*_*mus的帖子

Dart 中的 Mock http.Client 给出异常

我在测试发出 http 请求的类时遇到问题。我想模拟客户端,以便每次客户端发出请求时,我都可以用模拟响应进行回答。目前我的代码如下所示:

  final fn = MockClientHandler;
  final client = MockClient(fn as Future<Response> Function(Request));

  when(client.get(url)).thenAnswer((realInvocation) async =>
    http.Response('{"userId": 1, "id": 2, "title": "mock"}', 200));
Run Code Online (Sandbox Code Playgroud)

但是,当我运行测试时,出现以下异常: type '_FunctionType' is not a subtype of type '(Request) => Future<Response>' in type cast test/data_retrieval/sources/fitbit_test.dart 26:32 main

根据 Flutter/Dart Mockito 应该这样使用:

 final client = MockClient();

  // Use Mockito to return a successful response when it calls the
  // provided http.Client.
  when(client.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1')))
      .thenAnswer((_) async => http.Response('{"userId": 1, "id": 2, "title":"mock"}', 200));
Run Code Online (Sandbox Code Playgroud)

在示例中,客户端是在没有参数的情况下进行模拟的,但我想这已经发生了变化,因为 MockClient 的文档现在也接受参数。我不知道为什么会发生这个异常,并且在互联网上找不到任何内容,所以我想知道这里是否有人知道为什么会发生这个异常。

mockito dart dart-mock dart-http

4
推荐指数
1
解决办法
2737
查看次数

标签 统计

dart ×1

dart-http ×1

dart-mock ×1

mockito ×1