Skip to content

Instantly share code, notes, and snippets.

@rodrigolmacedo
Forked from hjJunior/dio_test.dart
Created October 8, 2020 18:24
Show Gist options
  • Save rodrigolmacedo/8b3ec7f4ece9121f04ea46874f21449d to your computer and use it in GitHub Desktop.
Save rodrigolmacedo/8b3ec7f4ece9121f04ea46874f21449d to your computer and use it in GitHub Desktop.
An example how to use mockito and Dio to tests your calls to API
class DioAdapterMock extends Mock implements HttpClientAdapter {}
const dioHttpHeadersForResponseBody = {
Headers.contentTypeHeader: [Headers.jsonContentType],
};
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, headers: dioHttpHeadersForResponseBody,);
when(dioAdapterMock.fetch(any, any, any)).thenAnswer((_) async => httpResponse);
final subject = await dataSource.login(userCredentials);
final expected = UserLoginResponse(token: 'token');
expect(subject, expected);
});
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment