Closed rrifafauzikomara closed 1 year ago
You must create a mock platform for shared preference testing. Your problem is not about get_it.
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);
});
}
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
Thanks guys for replying
Hi, I get this error when register
SharedPreferences
class.This is my widget testing.