Android 单元测试 / Mockito:android.location.Location 未模拟

use*_*382 5 junit android unit-testing mockito

我正在尝试在 Android 上学习基本的 JUnit 和 Mockito 测试。我正在尝试为一个简单的类编写单元测试,该类处理代表需要位置信息的活动从定位服务中查找用户的位置。

我一直在尝试创建“伪造位置”来测试:

@Test
public void testLocationReceived() throws Exception {
    Location fakeLocation = new Location(LocationManager.NETWORK_PROVIDER);
    fakeLocation.setLongitude(100);
    fakeLocation.setLatitude(-80);
    ...  
}
Run Code Online (Sandbox Code Playgroud)

但我收到错误:

java.lang.RuntimeException: Method setLongitude in android.location.Location not mocked.
Run Code Online (Sandbox Code Playgroud)

我知道 Android 上的单元测试在 JVM 上运行,因此您无法访问任何需要操作系统/框架的内容,但这也是其中一种情况吗?

  • 如果是这样,您如何判断哪些类可以/不可以在 JVM 上使用?
  • 除了基于 JVM 的单元测试之外,我现在是否还需要仪器/设备测试来测试这一类?

Joh*_*ang 5

build.gradle您应该在(应用程序)中添加以下内容:

testOptions {
        unitTests.returnDefaultValues = true
}
Run Code Online (Sandbox Code Playgroud)

更多详细信息:http://tools.android.com/tech-docs/unit-testing-support#TOC-Method-...-not-mocked.-

  • 并不能解决这个问题。你得到“null”而不是位置 (16认同)