提供了测试数据的共享preferences的Robolectric [英] Providing test data for SharedPreferences for Robolectric

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

问题描述

刚开始使用Robolectric,它似乎是pretty的太多我所需要的。不过,我已经打了一个有点路障的问候使用共享preferences。

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. 活动希望新的/空的共享preferences

  1. Activity expects a new/empty sharedPreferences

活动预计共享preferences在它的一些数据已经

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一些假数据,所以活动能够访问这个假数据。

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!

对于那些谁感兴趣的话,你只会得到共享preferences,并与所需的数据填充它。

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

如果你有一个自定义的共享preferences,你应该能够做到这一点(没有真正测试正常,但也应该)

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

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

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