为 Robolectric 的 SharedPreferences 提供测试数据 [英] Providing test data for SharedPreferences for Robolectric

查看:24
本文介绍了为 Robolectric 的 SharedPreferences 提供测试数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我有两个测试用例

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

  1. Activity expects a new/empty sharedPreferences

Activity 需要已经包含一些数据的 sharedPreferences

Activity expects sharedPreferences with some data in it already

对于测试用例 1,测试按预期通过,所以一切都很好:)

For Test Case 1, the tests are passing as expected, so all good :)

然而,对于测试用例 2,我似乎无法找到一种向 Robolectric 提供一些虚假数据的好方法,因此 Activity 能够访问这些虚假数据.

However, for Test Case 2 I can't seem to figure out a nice way to provide Robolectric with some fake data, so the Activity is able to access this fake data.

感觉这是一个很常见的用例,但我似乎不知道该怎么做!

It feels like a very common use case, but I can't seem to figure out how to do it!

推荐答案

找出方法 - 现在看起来很明显!

Found out how - seems so obvious now!

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

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();

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

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 :)

这篇关于为 Robolectric 的 SharedPreferences 提供测试数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆