我正在尝试在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上运行,所以你无法访问任何需要操作系统/框架的东西,但这也是这种情况之一吗?
答案 0 :(得分:3)
您应该在build.gradle
(app)中添加以下内容:
testOptions {
unitTests.returnDefaultValues = true
}
更多细节:http://tools.android.com/tech-docs/unit-testing-support#TOC-Method-...-not-mocked.-
答案 1 :(得分:1)
我和你有相同的铅。 @John Huang的回答帮助了我。您首先需要模拟位置,然后在何时放置所需的值时使用嘲笑。这是我的代码
@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
}
如果您的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}"