Providing test data for SharedPreferences for Robolectric

后端 未结 4 1027
醉梦人生
醉梦人生 2020-12-13 08:40

Just started to use Robolectric and it seems to be pretty much what I need. However, I\'ve hit a bit of a roadblock with regards to the use of SharedPreferences.

I h

相关标签:
4条回答
  • 2020-12-13 09:05

    Robolectric 3.1 SNAPSHOT solution that works for me... and may work for you

        Context context = RuntimeEnvironment.application.getApplicationContext();
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        sharedPreferences.edit().putBoolean("useOnlyOnWifi", false).commit();
    

    I use this snippet of code for only testing on wifi

    0 讨论(0)
  • 2020-12-13 09:10

    Found out how - seems so obvious now!

    For those who are interested, you just get the sharedPreferences, and populate it with the required data.

    SharedPreferences sharedPreferences = ShadowPreferenceManager.getDefaultSharedPreferences(Robolectric.application.getApplicationContext());
    sharedPreferences.edit().putString("testId", "12345").commit();
    

    If you have a custom SharedPreferences, you should be able to do this (haven't really tested properly, but should also work)

    SharedPreferences sharedPreferences = Robolectric.application.getSharedPreferences("you_custom_pref_name", Context.MODE_PRIVATE);
    sharedPreferences.edit().putString("testId", "12345").commit();
    

    Hope this has helped someone :)

    0 讨论(0)
  • 2020-12-13 09:19

    robolectric:4.0.2 use val context = ApplicationProvider.getApplicationContext<YourApplication>() PreferenceManager.getDefaultSharedPreferences(context)

    0 讨论(0)
  • 2020-12-13 09:25

    The accepted answer which I have up voted is right of course. Things have changed slightly if you are using Robolectric 3

     SharedPreferences sharedPreferences =
         RuntimeEnvironment.application.getSharedPreferences(
             "you_custom_pref_name", Context.MODE_PRIVATE);
    

    You can then add a preference as usual

     sharedPreferences.edit().putBoolean(
        activity.getString(R.string.pref_somepref), true).commit();
    
    0 讨论(0)
提交回复
热议问题