为Robolectric提供SharedPreferences的测试数据

pyk*_*yko 47 java android robolectric android-testing

刚刚开始使用Robolectric,它似乎是我所需要的.但是,我在使用SharedPreferences方面遇到了一些障碍.

我有两个测试用例

  1. Activity需要一个新的/空的sharedPreferences

  2. Activity期望sharedPreferences中包含一些数据

对于测试用例1,测试按预期传递,所以很好:)

但是,对于测试案例2,我似乎无法找到一个很好的方法来为Robolectric提供一些虚假数据,因此Activity能够访问这些假数据.

感觉就像一个非常常见的用例,但我似乎无法弄清楚如何做到这一点!

pyk*_*yko 57

发现了 - 现在看起来如此明显!

对于那些感兴趣的人,您只需获取sharedPreferences,并使用所需数据填充它.

SharedPreferences sharedPreferences = ShadowPreferenceManager.getDefaultSharedPreferences(Robolectric.application.getApplicationContext());
sharedPreferences.edit().putString("testId", "12345").commit();
Run Code Online (Sandbox Code Playgroud)

如果你有一个自定义的SharedPreferences,你应该能够做到这一点(没有真正测试过,但也应该工作)

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

希望这有助于某人:)

  • 我认为这应该是“PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application)” (2认同)

e4c*_*4c5 18

我所接受的答案当然是正确的.如果您使用Robolectric 3,情况会略有改变

 SharedPreferences sharedPreferences =
     RuntimeEnvironment.application.getSharedPreferences(
         "you_custom_pref_name", Context.MODE_PRIVATE);
Run Code Online (Sandbox Code Playgroud)

然后,您可以照常添加首选项

 sharedPreferences.edit().putBoolean(
    activity.getString(R.string.pref_somepref), true).commit();
Run Code Online (Sandbox Code Playgroud)


Eva*_*ons 8

Robolectric 3.1 SNAPSHOT解决方案适用于我......并且可能适合您

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

我使用这段代码只测试wifi


shu*_*ing 5

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