Skip to content

Error Register SharedPreferences in Widget Testing #314

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
rrifafauzikomara opened this issue Feb 17, 2023 · 4 comments
Closed

Error Register SharedPreferences in Widget Testing #314

rrifafauzikomara opened this issue Feb 17, 2023 · 4 comments

Comments

@rrifafauzikomara
Copy link

Hi, I get this error when register SharedPreferences class.

dart:async                                                        _Completer.completeError
package:shared_preferences/shared_preferences.dart 38:19          SharedPreferences.getInstance
===== asynchronous gap ===========================
dart:async                                                        _CustomZone.registerBinaryCallback
package:shared_preferences/shared_preferences.dart 33:13          SharedPreferences.getInstance
test/presentation/ui/profile/main_profile_screen_test.dart 20:51  main.<fn>.<fn>

PlatformException(channel-error, Unable to establish connection on channel., null, null)

This is my widget testing.

final sl = GetIt.instance;
void main() {
  group('MainProfileScreen test', () {
    late AppTestMaterialApp app;

    setUpAll(() async {
      TestWidgetsFlutterBinding.ensureInitialized();
      final preferences = await SharedPreferences.getInstance();
      sl.registerLazySingleton(() => preferences);

      ...

      app = AppTestMaterialApp(
        providers: [
          BlocProvider(
            create: (context) => ProfileBloc(
              profileUseCase: sl(),
              authUseCase: sl(),
              localization: sl(),
            ),
          ),
        ],
        home: const MainProfileScreen(),
      );
    });

    testWidgets('can render MainProfileScreen', (WidgetTester tester) async {
      await tester.pumpWidget(app.widget);
      await tester.pumpAndSettle();

      expect(find.byType(MainProfileScreen), findsOneWidget);
    });
  });

  tearDownAll(() {
    /// clear di after finish test
    sl.reset(dispose: true);
  });
}
@emintolgahanpolat
Copy link

emintolgahanpolat commented Mar 6, 2023

https://github.com/flutter/packages/blob/main/packages/shared_preferences/shared_preferences/test/shared_preferences_test.dart

You must create a mock platform for shared preference testing. Your problem is not about get_it.

@vousmeevoyez
Copy link

You need to create mock for shared preference.

import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'storage_test.mocks.dart'; // change depending on your test_file_name and generate it from bulid_runner

final sl = GetIt.instance;


@GenerateMocks([SharedPreferences])
void main() {
  group('MainProfileScreen test', () {
    late MockSharedPreferences mockSharedPreferences;
    late AppTestMaterialApp app;

    setUpAll(() async {
      TestWidgetsFlutterBinding.ensureInitialized();
      
       mockSharedPreferences = MockSharedPreferences();
      sl.registerLazySingleton(() => mockSharedPreferences);

      ...

      app = AppTestMaterialApp(
        providers: [
          BlocProvider(
            create: (context) => ProfileBloc(
              profileUseCase: sl(),
              authUseCase: sl(),
              localization: sl(),
            ),
          ),
        ],
        home: const MainProfileScreen(),
      );
    });

    testWidgets('can render MainProfileScreen', (WidgetTester tester) async {
       when(mockSharedPreferences.getString(any)).thenAnswer((_) => "hello");

      await tester.pumpWidget(app.widget);
      await tester.pumpAndSettle();

      expect(find.byType(MainProfileScreen), findsOneWidget);
    });
  });

  tearDownAll(() {
    /// clear di after finish test
    sl.reset(dispose: true);
  });
}

@vousmeevoyez
Copy link

You need to create mock for shared preference.

import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'storage_test.mocks.dart'; // change depending on your test_file_name and generate it from bulid_runner

final sl = GetIt.instance;


@GenerateMocks([SharedPreferences])
void main() {
  group('MainProfileScreen test', () {
    late MockSharedPreferences mockSharedPreferences;
    late AppTestMaterialApp app;

    setUpAll(() async {
      TestWidgetsFlutterBinding.ensureInitialized();
      
       mockSharedPreferences = MockSharedPreferences();
      sl.registerLazySingleton(() => mockSharedPreferences);

      ...

      app = AppTestMaterialApp(
        providers: [
          BlocProvider(
            create: (context) => ProfileBloc(
              profileUseCase: sl(),
              authUseCase: sl(),
              localization: sl(),
            ),
          ),
        ],
        home: const MainProfileScreen(),
      );
    });

    testWidgets('can render MainProfileScreen', (WidgetTester tester) async {
       when(mockSharedPreferences.getString(any)).thenAnswer((_) => "hello");

      await tester.pumpWidget(app.widget);
      await tester.pumpAndSettle();

      expect(find.byType(MainProfileScreen), findsOneWidget);
    });
  });

  tearDownAll(() {
    /// clear di after finish test
    sl.reset(dispose: true);
  });
}

@rrifafauzikomara

@escamoteur
Copy link
Collaborator

Thanks guys for replying

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants