我目前正在尝试为没有 UI(简单后台服务)的 Android 应用程序编写一些测试。我的 Android 服务基本上调用另一个类来处理大部分工作。我想测试这个类,但在其中我使用了类似的东西:
- 构建.SERIAL
- 构建.版本.发布
- BatteryManager.BATTERY_HEALTH_COLD
- 等等
创建 JSON 对象。
这些值在我的测试中为空,因为我试图在不依赖 Android 设备的情况下进行测试。有没有办法在测试期间模拟这些值或更改它们的默认值?我的测试真正想要验证的是我使用这些值构建的 JSON 对象是否正确构建。
最佳答案
Is there a way to mock these values or change their default values during the tests?
对于 Android,我们使用一个名为 Mockito 的库
做你想做的事情的一个简单方法是:
// create mock
YourBackgroundService test = Mockito.mock(YourBackgroundService.class);
// define return value for method getSerial()
when(test.getSerial()).thenReturn("42UNIV");
// use mock in test....
assertEquals(test.getSerial(), "42UNIV");
关于java - 为使用 android.os.Build 中的某些字段的 Android 应用程序编写测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39620142/