Home > database >  How can I verify that a request has been made using http_mock_adapter?
How can I verify that a request has been made using http_mock_adapter?

Time:11-25

I'm using http_mock_adaper to mock Dio HTTP requests. That part works fine, but the thing I am having problems with is verifying that a request has been made using.

One idea I had was to call mockito's verify() with dio.get(any) or adapter.onGet(any, any) as a parameter, but that obviously won't work, since those classes are not mocked using mockito.

Another option I have is to mock the class that calls dio, but that means that I would have to stub every method that is called (Again, since the actual HTTP calls have already been mocked), and I would like to avoid that if possible.

Is there a way to verify that a HTTP call has been made with http_mock_adaper, or is my last option the only / best solution?

CodePudding user response:

Just an example of a base idea. But it can be flexible enough(also for errors and responses).

What if we create our own Interceptor for test purpouse:

class TestHistoryInterceptor extends Interceptor {
  final requests = <String>[];

  TestHistoryInterceptor();

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    requests.add(options.path);

    handler.next(options);
  }

  @override
  void one rror(DioError err, ErrorInterceptorHandler handler) {
    // err.requestOptions.path

    handler.next(err);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    // response.requestOptions.path

    handler.next(response);
  }

  void clear() {
    requests.clear();
  }
}

and we can use it(changed example from http_mock_adapter repo):

void main() async {
  late Dio dio;
  late DioAdapter dioAdapter;
  //#1
  final testHistoryInterceptor = TestHistoryInterceptor();

  Response<dynamic> response;

  group('Accounts', () {
    const baseUrl = 'https://example.com';

    const userCredentials = <String, dynamic>{
      'email': '[email protected]',
      'password': 'password',
    };

    setUp(() {
      dio = Dio(BaseOptions(baseUrl: baseUrl));
      dioAdapter = DioAdapter(dio: dio);
      //#2
      dio.interceptors.add(testHistoryInterceptor);
    });

    tearDown(() {
      //#3
      dio.interceptors.remove(testHistoryInterceptor);
      testHistoryInterceptor.clear();
    });

    test('signs up user', () async {
      const route = '/signup';

      dioAdapter.onPost(
        route,
            (server) => server.reply(201, null),
        data: userCredentials,
      );

      // Returns a response with 201 Created success status response code.
      response = await dio.post(route, data: userCredentials);

      //#4
      expect(testHistoryInterceptor.requests, ["/signup"]);

      expect(response.statusCode, 201);
    });

    //...
  });
}
  • Related