Android单元测试/ Mockito:android.location.Location not micked

inb24sb2  于 9个月前  发布在  Android
关注(0)|答案(3)|浏览(88)

我正在尝试学习在Android上进行基本的JUnit和Mockito测试。我正在尝试为一个简单的类编写单元测试,这个类代表需要位置信息的活动处理从位置服务查找用户位置的问题。
我一直在尝试创建“假位置”来测试:

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

但我得到了错误:

java.lang.RuntimeException: Method setLongitude in android.location.Location not mocked.

我知道Android上的单元测试运行在JVM上,所以你不能访问任何需要操作系统/框架的东西,但这也是其中之一吗?

  • 如果是这样的话,你怎么知道什么类可以/不能在JVM上使用?
  • 除了基于JVM的单元测试之外,我现在还需要仪器/设备测试来测试这个类吗?
3okqufwl

3okqufwl1#

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

testOptions {
        unitTests.returnDefaultValues = true
}

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

wyyhbhjk

wyyhbhjk2#

我和你有一样的肺结核。@John Huang的回答帮了我。你首先需要模拟的位置,然后使用mockito时,把你想要的值。

@RunWith(PowerMockRunner::class)
class MapExtensionTest {
 @Mock
    private lateinit var location: Location

    //region calculateDistance
    @Test
    fun `given a valid store and a valid location  to calculateDistance should return the correct distance`() {
        Mockito.`when`(store.coordinate).thenReturn(coordinate)
        Mockito.`when`(coordinate.latitude).thenReturn(FAKE_LAT)
        Mockito.`when`(coordinate.longitude).thenReturn(FAKE_LON)
        Mockito.`when`(location.latitude).thenReturn(FAKE_LAT1)
        Mockito.`when`(location.longitude).thenReturn(FAKE_LON1)
        val result = FloatArray(1)
        Location.distanceBetween(
            store.coordinate.latitude,
            store.coordinate.longitude,
            location.latitude, location.longitude, result
        )

        store.calculateDistance(location)

        Assert.assertTrue(store.distance == result[0].toDouble())
    }

别忘了约翰说的

testOptions {
    unitTests.returnDefaultValues = true
}

如果你有带import的pb,这里是我的测试依赖项,但我不记得哪个对这个例子很重要,所以请记住,你可能不需要所有的

//testing dependencies
testImplementation "junit:junit:$junitVersion"
testImplementation "org.mockito:mockito-inline:${mockitoInlineVersion}"
testImplementation "androidx.arch.core:core-testing:${coreTestingVersion}"
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:${mockitoKotlinVersion}"
androidTestImplementation "org.mockito:mockito-android:${mockitoAndroidVersion}"
testImplementation group: 'org.powermock', name: 'powermock-api-mockito2', version: "${powerMockMockitoVersion}"
testImplementation group: 'org.powermock', name: 'powermock-module-junit4', version: "${powerMockjUnitVersion}"
ztigrdn8

ztigrdn83#

使用Robolectric测试转轮为我解决了这个问题。

@RunWith(RobolectricTestRunner::class)
class TestClass {
   ...
}

注意:我不需要

testOptions {
        unitTests.returnDefaultValues = true
}

如果您的项目中还没有Robolectric依赖项,请不要忘记添加必要的Robolectric依赖项。

相关问题