android - 还有其他方法可以为 Android 测试模拟 SharedPreferences 吗?

标签 android unit-testing android-testing robolectric android-instrumentation

我正在使用 Espresso 为 Android 应用程序编写 UI 测试。但存在一个问题,即无法模拟 SharedPreferences 数据。我找到了一些解决方法,但它们使用的是依赖项注入(inject)(主要是 Dagger2)。

有没有什么方法可以在没有任何依赖注入(inject)的情况下模拟首选项? 也许存在另一个适合它的测试框架?

编辑: 我需要在检测中模拟 SharedPreferences,而不是单元测试。

最佳答案

查看 Robolectric .然后你会这样做:

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

来自official website :

Robolectric is a unit test framework that de-fangs the Android SDK jar so you can test-drive the development of your Android app. Tests run inside the JVM on your workstation in seconds.

关于android - 还有其他方法可以为 Android 测试模拟 SharedPreferences 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43118317/

相关文章:

android - Android中的自定义 tensorflow 模型

c++ - 依赖网络时的 Qt 测试

从 R.attr 引用返回颜色资源 ID 的 Android 测试方法

android - 澄清 Firebase 连接

android - 如何在TextView中的文本末尾显示光标?

android - 在哪个生命周期方法中,我们应该观察一个 livedata 对象?

java - 如何在不访问私有(private)变量的情况下测试 jUnit 测试中的时间流逝?

c# - 访问私有(private)字段

android-intent - Android espresso 匹配意图与 bundle 内的 bundle

javascript - UIautomation 中的不同输入无需手动修改脚本