Ask Your Question
2

How to imitate Http Client calls during flutter testing?

asked 2021-06-04 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-06-22 05:00:00 +0000

pufferfish gravatar image

To imitate HTTP client calls during Flutter testing, you can use a package called mockito. Here's how you can use it:

  1. First, add the mockito package to your pubspec.yaml file:
dev_dependencies:
  mockito: any
  1. Import the mockito package in your test file:
import 'package:mockito/mockito.dart';
  1. Create a mock HTTP client:
class MockClient extends Mock implements http.Client {}
  1. Use the mock client in your test case:
test('Test HTTP request', () async {
  final mockClient = MockClient();

  // Create a response that the mock client will return
  final response = http.Response('{"data": "Hello World"}', 200);

  // Use the `when` method from `mockito` to mock the request
  when(mockClient.get('http://example.com/data'))
      .thenAnswer((_) async => response);

  // Make the HTTP request with the mock client
  final myData = await fetchData(mockClient);

  expect(myData.data, equals('Hello World'));
});

In this example, we're mocking a HTTP GET request to http://example.com/data. We use the when method from mockito to tell the mock client what to return when this request is made. We then make the HTTP request using a function called fetchData that takes an HTTP client as a parameter. Finally, we assert that the data returned by the fetchData function is equal to 'Hello World'.

By using mockito to mock HTTP requests, we can test our code without actually making real HTTP requests. This makes our tests faster and more reliable.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-06-04 11:00:00 +0000

Seen: 18 times

Last updated: Jun 22 '21