Skip to content

Instantly share code, notes, and snippets.

@hjJunior
Created November 2, 2019 19:03
Show Gist options
  • Save hjJunior/1ea524be7f0d09e5b1639e46560f44f0 to your computer and use it in GitHub Desktop.
Save hjJunior/1ea524be7f0d09e5b1639e46560f44f0 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);
});
});
});
}
@shan-shaji
Copy link

How can I mock the post method of dio

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment