Dio tests with Mockito.
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));
You can custom adapter to mock. A test example is here.
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.
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.
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 can I ask for gist of the mocking?
i've tried dio with mockito , you can check in here,
may be can help you @bmatheus91
@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.
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.
I'm trying to use Mockito to create a mocked Adapter, but I'm getting an exception
The example
- I defined
DioAdapterMockas subclass of Mock - I create instance of mock
- 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)
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,
You can use http-mock-adapter.
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>()));
});
});
}
Thank you @bmatheus91 but how can i do this with get method?
Thanks @bmatheus91 this is useful when using with named argument option:
when(mockHttpClient.get('url', options: anyNamed('options'))).thenAnswer(...);
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.