簡體   English   中英

為Robolectric提供SharedPreferences的測試數據

[英]Providing test data for SharedPreferences for Robolectric

剛剛開始使用Robolectric,它似乎是我所需要的。 但是,我在使用SharedPreferences方面遇到了一些障礙。

我有兩個測試用例

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

  2. Activity期望sharedPreferences中包含一些數據

對於測試用例1,測試按預期傳遞,所以很好:)

但是,對於測試用例2,我似乎無法找到一個很好的方法來為Robolectric提供一些假數據,因此Activity能夠訪問這些假數據。

感覺就像一個非常常見的用例,但我似乎無法弄清楚如何做到這一點!

發現了 - 現在看起來如此明顯!

對於那些感興趣的人,您只需獲取sharedPreferences,並使用所需數據填充它。

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

如果你有一個自定義的SharedPreferences,你應該能夠做到這一點(沒有真正測試過,但也應該工作)

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

希望這有助於某人:)

我所投票的已接受的答案當然是正確的。 如果您使用Robolectric 3,情況會略有改變

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

然后,您可以照常添加首選項

 sharedPreferences.edit().putBoolean(
    activity.getString(R.string.pref_somepref), true).commit();

Robolectric 3.1 SNAPSHOT解決方案對我有用......並且可能適合您

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

我使用這段代碼只測試wifi

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM