Created
November 2, 2019 19:03
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
How can I mock the post method of dio