DrkStr
DrkStr

Reputation: 1932

Trouble with testing using MockClient in Flutter

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.

Upvotes: 6

Views: 2127

Answers (2)

yla-dev
yla-dev

Reputation: 144

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

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

Upvotes: 4

Moacir Schmidt
Moacir Schmidt

Reputation: 945

Mock expects test function to be EXACTLY as you real function (including OPTIONAL parameters and so on). If both does not match it returns NULL and that is what is happening with your code. Double check to see where your test function is different of original function.

Upvotes: 0

Related Questions