6

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.

2 Answers 2

4

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

return Response(json.encode(jsonMap), 200);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.