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 から何も返されないことだと思いますが、その理由はわかりません。