【发布时间】:2021-09-04 23:13:59
【问题描述】:
我在测试发出 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));
但是,当我运行测试时,出现以下异常:
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));
在示例中,客户端是在没有参数的情况下模拟的,但我想这已经改变了,因为 MockClient 的文档现在也接受了参数。 我不知道为什么会发生此异常,并且在 Internet 上找不到任何内容,所以我想知道这里是否有人知道为什么会发生此异常。
【问题讨论】:
-
我怀疑问题出在
final fn = MockClientHandler;,后来你又做了fn as Future<Response> Function(Request)。MockClientHandler是什么?听起来它是typedef(这将使其成为 type)而不是Function的实例,这会导致强制转换失败。 -
但是当我不添加演员表时,它会出现编译错误:
The argument type 'Type' can't be assigned to the parameter type 'Future<Response> Function(Request)'.你能帮我看看演员表应该是什么样子吗? -
你没有抓住重点。
final fn = MockClientHandler;出了什么问题。 (这最终是一个无用的任务。之后你可以用fn做任何有意义的事情。)再一次:MockClientHandler是什么?目前尚不清楚您对fn的期望是什么。 -
啊,
MockClient和MockClientHandler由package:http的测试库提供。正如我所怀疑的,您需要提供一个实际的功能。
标签: dart mockito dart-http dart-mock