robolectric - 使用 robolectric 更改某些资源字符串

标签 robolectric

我有一个可以工作的 robolectric,并且想要测试我的应用程序中执行 HTTP 请求的组件。由于我不希望这些请求发送到我的实时服务器,而是发送到本地测试服务器,因此我想在测试期间覆盖字符串资源(包含服务器主机名)。

但是,我无法在 robolectric 文档中找到任何朝着我想要的方向远程运行的内容:(

最佳答案

我在 Robolectric 3 中遇到过类似的问题;您可以使用 Mockito 部分模拟覆盖应用程序级别的资源。

首先,您告诉 Robolectric 使用部分模拟的应用程序,并在使用应用程序上下文时返回它:(感谢这个答案:https://stackoverflow.com/a/31386831/327648)

RuntimeEnvironment.application = spy(RuntimeEnvironment.application);
when(RuntimeEnvironment.application.getApplicationContext())
    .thenReturn(RuntimeEnvironment.application);

然后你部分地模拟 Resources 对象:

Resources spiedResources = spy(app.getResources());
when(app.getResources())
    .thenReturn(spiedResources);

然后你可以做真正的覆盖:

when(spiedResources.getString(R.string.server_address))
    .thenReturn("local server address");

我希望这会有所帮助。

关于robolectric - 使用 robolectric 更改某些资源字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19682102/

相关文章:

android - 线程上的 robolectric runOnUiThread 不起作用

android - Robolectric 断言因共享首选项 android 而失败

android - 使用 Robolectric 和 Mockito 对 Realm + Dagger 2 进行单元测试

android - ClassCastException : NoClassDefFoundError cannot be cast to RuntimeException

android - FragmentManager.getFragmentFactory 的 NoSuchMethodError

android - Robolectric+Eclipse 找不到资源?

android - Robolectric getPixel 始终返回 0

android - 机器人 "INTERNET permission is required"

android - Gradle + Robolectric : Where do I put the file org. robolectric.Config.properties?

Android Robolectric 异常