我正在尝试学习基本的JUnit和Mockito测试在安卓上。我试图为一个简单的类编写单元测试,它代表需要位置信息的活动处理从location中查找用户的位置。
我一直试图创建“伪造位置”来进行测试:
@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上,所以您没有访问任何需要操作系统/框架的权限,但这也是其中一种吗?
发布于 2016-05-07 12:59:17
您应该在build.gradle (App)中添加以下内容:
testOptions {
unitTests.returnDefaultValues = true
}更多细节:http://tools.android.com/tech-docs/unit-testing-support#TOC-Method-...-not-mocked.-
发布于 2020-05-28 08:57:09
我有和你一样的铅。约翰·黄的回答帮助了我。您首先需要模拟这个位置,然后使用mockito将您想要的值放入.here是我的代码。
@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}"https://stackoverflow.com/questions/36832001
复制相似问题