russhwolf / multiplatform-settings

A Kotlin Multiplatform library for saving simple key-value data
Apache License 2.0
1.7k stars 67 forks source link

How to use testing in unit test by Koin #143

Closed johncheung233 closed 1 year ago

johncheung233 commented 1 year ago

Could not create instance for '[Singleton:'com.russhwolf.settings.Settings',qualifier:normal]

actual val settingsModule: Module = module { single(named("encrypted")) { val context = get() val masterKey = MasterKey.Builder(context) .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) .build() val delegate = EncryptedSharedPreferences.create( context, "encrypted", masterKey, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) SharedPreferencesSettings(delegate) } single(named("normal")) { val context = get() val delegate : SharedPreferences = context.getSharedPreferences("normal", Context.MODE_PRIVATE) SharedPreferencesSettings(delegate) } single{ val context = get() KMMPreference(context) } }

russhwolf commented 1 year ago

Most Context-based things aren't going to work in a unit test, unless you're using something like Robolectric. That isn't really anything to do with this library.

You can substitute MapSettings in your tests instead of SharedPreferencesSettings to get a Settings instance that's in-memory only and doesn't depend on Context.