Skip to content

Instantly share code, notes, and snippets.

@hjJunior
Created November 2, 2019 19:03
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

@V3ntus
Copy link

V3ntus commented Jan 7, 2025

For posterity, mockito now requires you to utilize the GenerateMocks/GenerateNiceMocks annotations because of Dart null safety. Here is my test file:

auth_test.dart
import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutunes/api/client.dart';
import 'package:flutunes/models/user.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';

import 'auth_test.mocks.dart';

class MockDio extends Mock implements Dio {}

@GenerateMocks([MockDio])
void main() {
  group(
    "auth",
    () {
      late final JellyfinClient client;
      late final MockMockDio mockDio;

      setUp(() async {
        TestWidgetsFlutterBinding.ensureInitialized();
        SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.withData({
          "SERVER_ROOT": TEST_ROOT_URL,
        });
        mockDio = MockMockDio();
        client = JellyfinClient(dio: mockDio);
      });

      test(
        'login returns a User model on success',
        () async {
          const testUserUUID = "5b9720dd-f1c6-4fe8-9de2-b7d746469529";
          const loginPath = "/Users/AuthenticateByName";
          const Map<String, dynamic> loginResult = {
            "User": {
              "Name": "USER_NAME_TEST",
              "ServerId": "USER_SERVER_ID_TEST",
              "ServerName": "USER_SERVER_NAME_TEST",
              "PrimaryImageTag": "PRIMARY_IMAGE_TAG_TEST",
              "Id": testUserUUID,
              "EnableAutoLogin": true,
            },
            "SessionInfo": {},
            "AccessToken": "ACCESS_TOKEN_TEST",
            "ServerId": "SERVER_ID_TEST",
          };

          when(mockDio.post(TEST_ROOT_URL + loginPath, data: anyNamed("data"))).thenAnswer(
            (_) async => Response(
              data: loginResult,
              requestOptions: RequestOptions(path: loginPath),
              statusCode: 200,
            ),
          );


          expect(await client.authenticateByName("", ""), isA<UserModel>());
          expect((await client.authenticateByName("", "")).json, equals(loginResult["User"]));
        },
      );
    },
  );
}

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