dio icon indicating copy to clipboard operation
dio copied to clipboard

Dio tests with Mockito.

Open bmatheus91 opened this issue 7 years ago • 15 comments

How can i mock Dio requests with Mockito?

Would like to do something like this:

when( client.post(Api.BASE_URL_AUTH + "/auth", data: credentials.toJson(), options: Options(headers: { 'Content-type': 'application/json', 'Accept': 'application/json' }))).thenAnswer((_) async => Response(data: { "data": { "id": "5d166a5e9081294ed4b71016", "personCode": "221205", "username": "user.mock", } }, statusCode: 200));

bmatheus91 avatar Jul 11 '19 12:07 bmatheus91

You can custom adapter to mock. A test example is here.

wendux avatar Jul 16 '19 09:07 wendux

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, please make sure it is up to date and if so, add a comment that this is still an issue to keep it open. Thank you for your contributions.

stale[bot] avatar Aug 15 '19 10:08 stale[bot]

actually the mocking works without the Options. Feels weird that after adding Options, Dio can't be mocked / only return null if mocked. As a workaround, I introduced another layer for Dio. @wendux The example is great, but with ability to mock Dio request with Mockito makes user can mock the request easier.

yuzurihaaa avatar Aug 19 '19 15:08 yuzurihaaa

Actually i achieved Mocking requests with Dio and using options. As soon i'm available i will try to write a post on Medium about it

bmatheus91 avatar Aug 20 '19 19:08 bmatheus91

@bmatheus91 can I ask for gist of the mocking?

yuzurihaaa avatar Sep 17 '19 01:09 yuzurihaaa

i've tried dio with mockito , you can check in here, may be can help you @bmatheus91

cahyofendhi avatar Sep 25 '19 06:09 cahyofendhi

@cahyofendhi thanks for the suggestion, but from the example, dio is wrapped in another class (in this case Service class) and that instance is the one that is mocked. Yeah, it does do the work (and currently I am doing it this way too). But I am looking for direct mock to dio. cheers.

yuzurihaaa avatar Sep 25 '19 09:09 yuzurihaaa

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, please make sure it is up to date and if so, add a comment that this is still an issue to keep it open. Thank you for your contributions.

stale[bot] avatar Oct 25 '19 09:10 stale[bot]

I'm trying to use Mockito to create a mocked Adapter, but I'm getting an exception

The example

  1. I defined DioAdapterMock as subclass of Mock
  2. I create instance of mock
  3. And I mock the calls for dioAdapterMock.fetch
class DioAdapterMock extends Mock implements HttpClientAdapter {}

void main() {
 group('UserRemoteDataSource', () {
   final Dio dio = Dio();
   UserRemoteDataSource dataSource;
   DioAdapterMock dioAdapterMock;

   setUp(() {
     dioAdapterMock = DioAdapterMock();
     dio.httpClientAdapter = dioAdapterMock;
     dataSource = UserRemoteDataSource(dio);
   });

   group('login', () {
     test('when credentials are valid should return UserLoginResponse with token', () async {
       final userCredentials = UserLoginRequestBody(password: 'password', email: 'email');
       final responsePayload = json.encode({ 'token': 'token' });
       final httpResponse = ResponseBody.fromString(responsePayload, 200);

       when(dioAdapterMock.fetch(any, any, any)).thenAnswer((_) async => httpResponse);

       final subject = await dataSource.login(userCredentials);
       final expected = UserLoginResponse(token: 'token');

       expect(subject, expected);
     });
   });
 });
}

The Exception

It looks a casting exception, but I can't get the reason, since I'm using json.encode to convert my map to String

package:dio/src/dio.dart 886:9  DioMixin._request.<fn>
dart:async                      _completeOnAsyncReturn
package:dio/src/dio.dart        DioMixin._dispatchRequest
===== asynchronous gap ===========================
dart:async                      Future.catchError
package:dio/src/dio.dart 884:8  DioMixin._request

DioError [DioErrorType.DEFAULT]: type 'String' is not a subtype of type 'Map<String, dynamic>'
#0      DioMixin.assureResponse (package:dio/src/dio.dart:1120:9)
#1      DioMixin._request.<anonymous closure> (package:dio/src/dio.dart:883:14)
#2      StackZoneSpecification._registerUnaryCallback.<anonymous closure>.<anonymous closure> (package:stack_trace/src/stack_zone_specification.dart:129:26)
#3      StackZoneSpecification._run (package:stack_trace/src/stack_zone_specification.dart:209:15)
#4      StackZoneSpecification._registerUnaryCallback.<anonymous closure> (package:stack_trace/src/stack_zone_specification.dart:129:14)

hjJunior avatar Nov 02 '19 18:11 hjJunior

Update

I just updated the ResponseBody to pass the headers and define contentType and it solved!

final httpResponse = ResponseBody.fromString(responsePayload, 200, headers: {
  Headers.contentTypeHeader: [Headers.jsonContentType],
},);

I created an gist, which there is the complete code that I used,

hjJunior avatar Nov 02 '19 19:11 hjJunior

As requested, this is how i do my tests with Dio and Mockito

api_task.dart

class APITask {
  static final _log = Logger('APITaskDatasource');

  final Dio client;

  APITask({this.client});

  @override
  Future<void> updateTask(Task task) async {
    await client.patch(
      url: '/v1/calendar/tasks/${task.id}status=${TaskStateExtension.getString(task.state)}&finish=$now',
    );
  }
}

api_task_test.dart

class MockDioClient extends Mock implements Dio {}

void main() {
  Dio client;
  APITask source;

  setUp(() {
    client = MockDioClient();
    source = APITask(client);
  });

  group('updateTaskState', () {
    test('should update Task state with correct given ID and Status', () async {
      when(client.patch(any, queryParameters: anyNamed('queryParameters')))
          .thenAnswer((realInvocation) async =>
              Response(data: json.decode(fixture('task.json'))));

      await source.updateTaskState('7dYZkG4ZMSBseIz6uwVr',
          state: TaskState.accepted);

      verify(client.patch('/v1/calendar/tasks/7dYZkG4ZMSBseIz6uwVr',
          queryParameters: {'status': 'ACCEPTED'}));
      verifyNoMoreInteractions(client);
    });

    test('should throw a Exception when the request fails', () async {
      when(client.patch(any, queryParameters: anyNamed('queryParameters')))
          .thenThrow(DioError(
              request:
                  RequestOptions(method: 'PATCH', path: '/v1/calendar/tasks'),
              response: Response(
                  statusCode: 400, statusMessage: 'Falha na requisição')));

      expect(
          () async => await source.updateTaskState('7dYZkG4ZMSBseIz6uwVr',
              state: TaskState.accepted),
          throwsA(TypeMatcher<DioError>()));
    });
  });
}

bmatheus91 avatar May 06 '21 16:05 bmatheus91

Thank you @bmatheus91 but how can i do this with get method?

shan-shaji avatar Jun 22 '21 07:06 shan-shaji

Thanks @bmatheus91 this is useful when using with named argument option:

when(mockHttpClient.get('url',  options: anyNamed('options'))).thenAnswer(...);

mateuscelio avatar Nov 09 '21 23:11 mateuscelio

Thanks @bmatheus91 this is useful when using with named argument option:

when(mockHttpClient.get('url',  options: anyNamed('options'))).thenAnswer(...);

Thanks a lot and appreciate it, your answer helped me to resolve a unit test which I have been fighting to solve it.

JeganGitHub avatar Mar 18 '23 16:03 JeganGitHub