import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:nontonki/core/config/locale_controller.dart'; import 'package:shared_preferences/shared_preferences.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'; void main() { setUp(() { SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); }); test('no stored choice keeps the device locale', () async { final controller = LocaleController(); var notifications = 0; controller.addListener(() => notifications++); await controller.load(); expect(controller.locale, isNull); expect(notifications, 1); }); test('a chosen language survives a restart', () async { final first = LocaleController(); await first.select('zh'); expect(first.locale, const Locale('zh')); final reopened = LocaleController(); await reopened.load(); expect(reopened.locale, const Locale('zh')); }); test('selecting english clears a stored chinese preference', () async { await LocaleController().select('zh'); final reopened = LocaleController(); await reopened.load(); await reopened.select('en'); final third = LocaleController(); await third.load(); expect(third.locale, const Locale('en')); }); test('an unsupported code clears the locale instead of throwing', () async { final controller = LocaleController(); await controller.select('zh'); expect(controller.locale, const Locale('zh')); await controller.select('tlh'); expect(controller.locale, isNull); }); test('an unsupported stored code resolves to the device locale', () async { await SharedPreferencesAsync().setString('ui.locale', 'fr'); final controller = LocaleController(); await controller.load(); expect(controller.locale, isNull); }); test('a broken preference store never breaks load or select', () async { SharedPreferencesAsyncPlatform.instance = _BrokenPreferences(); final controller = LocaleController(); await controller.load(); expect(controller.locale, isNull); await controller.select('zh'); expect(controller.locale, const Locale('zh')); }); } /// Stands in for a platform whose preference store is unavailable. base class _BrokenPreferences extends InMemorySharedPreferencesAsync { _BrokenPreferences() : super.empty(); @override Future getString(String key, SharedPreferencesOptions options) => Future.error(StateError('preferences unavailable')); @override Future setString( String key, String value, SharedPreferencesOptions options, ) => Future.error(StateError('preferences unavailable')); }