所以我有存储库,它向客户端提供Observable。有没有一种方法可以模拟此存储库,因此我不需要从模拟器发送位置或使用真实设备来获取某些位置?
界面如下所示:
interface RxLocationRepository {
@SuppressLint("MissingPermission")
fun onLocationUpdate(): Observable<Location>
fun stopLocationUpdates()
}
在我的客户端,我这样使用:
class LocationManager(
val rxLocationRepository: RxLocationRepository){
private fun appendGeoEvent(location: Location) {
val locationGeoEvent = LocationGeoEvent(
accuracy = location.accuracy.toDouble(),
latitude = location.latitude,
longitude = location.longitude,
timestampGeoEvent = location.time
)
processGeoEvent(locationGeoEvent)
}
compositeDisposable.add(rxLocationRepository.onLocationUpdate()
.subscribe(Consumer { location ->
appendGeoEvent(location)
}))
....
所以我将此获取的位置发送到我的appendGeoEvent方法。
我可以使用例如Mockito,但我不知道如何模拟此存储库,因此我可以使用假位置。
另外,我想使用Kotlin。
最佳答案
如果使用Mockito,则可以执行以下操作:
import android.location.Location
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.mockito.junit.MockitoJUnitRunner
import java.util.*
@RunWith(MockitoJUnitRunner::class)
class LocationsTest{
@Test
fun should_return_one_location() {
val location = Location("test").apply {
latitude = 1.234
longitude = 5.678
// ...
}
val mockRepository = mock(RxLocationRepository::class.java)
`when`(mockRepository.onLocationUpdate()).thenReturn(Observable.just(location))
// use the mock
}
}
我正在使用:
testCompile "org.mockito:mockito-core:2.11.0"
关于unit-testing - 如何模拟返回Observable的响应式(Reactive)存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46935260/