Drk*_*Str 6 flutter flutter-test
我正在尝试使用 MockClient 在 flutter 中编写一个简单的测试,但我似乎无法让它工作。
这是我试图测试的代码:
getItemById(int id) async {
final response = await client.get("$_host/item/$id.json");
final decodedJson = json.decode(response.body);
return Item.fromJson(decodedJson);
}
Run Code Online (Sandbox Code Playgroud)
这是测试代码:
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);
});
Run Code Online (Sandbox Code Playgroud)
当我运行测试时,它失败并显示以下消息:
NoSuchMethodError: The getter 'bodyBytes' was called on null.
Receiver: null
Tried calling: bodyBytes
Run Code Online (Sandbox Code Playgroud)
我猜测这里的问题是,当我调用 getItemById 方法时,MockClient 没有返回任何内容,但我不确定为什么。
我有同样的问题。您必须返回响应
return Response(json.encode(jsonMap), 200);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2071 次 |
| 最近记录: |