我正在尝试使用 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 没有返回任何内容,但我不知道为什么。