Trouble with testing using MockClient in Flutter

Issue

I am trying to write a simple test in flutter using MockClient, but I can’t seem to get it to work.

Here is the code I am trying to test:

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

   return Item.fromJson(decodedJson);
}

Here is the test code:

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);
});

When I run the test, it fails with the following message:

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

I am guessing the issue here is that nothing is returned from the MockClient when I make the call to the getItemById method, but I am not sure why.

Solution

I had the same exact issue. You have to return the Response

return Response(json.encode(jsonMap), 200);

Answered By – yla-dev

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.