4

我正在尝试使用 MockClient 在颤振中编写一个简单的测试,但我似乎无法让它工作。

这是我要测试的代码:

getItemById(int id) async {
   final response = await client.get("$_host/item/$id.json");
   final decodedJson = json.decode(response.body);

   return Item.fromJson(decodedJson);
}

这是测试代码:

test("Test getting item by id", () async {
   final newsApi = NewsAPI();
   newsApi.client = MockClient((request) async {
      final jsonMap = {'id': 123};
      Response(json.encode(jsonMap), 200);
   });

   final item = await newsApi.getItemById(123);
   print("Items:  ${item.toString()}"); //<-- dosen't print anything. 
   expect(item.id , 123);
});

当我运行测试时,它失败并显示以下消息:

 NoSuchMethodError: The getter 'bodyBytes' was called on null.
 Receiver: null
 Tried calling: bodyBytes

我猜这里的问题是当我调用 getItemById 方法时,MockClient 没有返回任何内容,但我不知道为什么。

4

2 回答 2

3

我有同样的问题。您必须返回响应

return Response(json.encode(jsonMap), 200);
于 2019-07-21T16:51:24.810 回答
0

Mock 期望测试功能与您的实际功能完全相同(包括可选参数等)。如果两者都不匹配,则返回 NULL,这就是您的代码所发生的情况。仔细检查以查看您的测试功能与原始功能不同的地方。

于 2019-05-03T06:34:54.767 回答