简体   繁体   中英

Flutter how to unit test Dio 401, 500 responses

Currently I'm testing 200 responses as following

final dio = Dio();
final dioAdapter = DioAdapter();
dio.httpClientAdapter = dioAdapter;
const path = 'https://endpoint.com';

test('Loading shows when user taps set up trading account', () async {
  dioAdapter
    ..onPost(
      path,
      (request) => request.reply(204, {}),
    );

  final onGetResponse = await dio.post(path);

  when(_tradingAccountService.setUpTradingAccount())
      .thenAnswer((realInvocation) => Stream.value(HttpResponse(onGetResponse.data, onGetResponse)));
  await signUpViewModel.setUpTradingAccount();
  expect(signUpViewModel.isSettingUpTradingAccount, true);
});

But when I try to test 401 or 500, dio throws HttpStatusError

 final dioError = DioError(
        error: {'message': 'Some beautiful error!'},
        requestOptions: RequestOptions(path: '/foo'),
        response: Response(
          statusCode: 500,
          requestOptions: RequestOptions(path: '/foo'),
        ),
    type: DioErrorType.response,
  );

  dioAdapter.onPost(
    path,
    (request) => request.throws(500, dioError),
  );

I was hoping to do something like this

 when(_tradingAccountService.setUpTradingAccount())
          .thenAnswer((realInvocation) => Stream.value(HttpResponse(204)));

Those didn't help How create test for dio timeout and https://github.com/flutterchina/dio/blob/master/dio/test/mock_adapter.dart

Use http_mock_adapter ,package for mocking Dio requests.

You can simply replace your injected Dio 's httpClientAdapter with DioAdapter() of http_mock_adapter :

example from examples of http_mock_adapter

Usage

Here is the basic usage scenario of the package (via DioAdapter ):

import 'package:dio/dio.dart';
import 'package:http_mock_adapter/http_mock_adapter.dart';

void main() async {
  final dio = Dio();
  final dioAdapter = DioAdapter();

  dio.httpClientAdapter = dioAdapter;

  const path = 'https://example.com';

  dioAdapter
      ..onGet(
        path,
        (request) => request.reply(200, {'message': 'Successfully mocked GET!'}),
      )
      ..onGet(
        path,
        (request) => request.reply(200, {'message': 'Successfully mocked POST!'}),
      );

  final onGetResponse = await dio.get(path);
  print(onGetResponse.data); // {message: Successfully mocked GET!}

  final onPostResponse = await dio.post(path);
  print(onPostResponse.data); // {message: Successfully mocked POST!}
}

Note:

There was a fixed kinda issue please take a look at it there, I guess it would be helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM