After I updated my phone to Android 12, my app (TargetSDKVersion 29) stopped to get location updates. So I have to update the app to API 31.
For this I want to write some instrumented tests for the location updates. I started with the simple test for requestLocationUpdates()
. But in this simple test I don't get any location update.
Just in case I also adjusted the timestamps to 5s intervals to simulate some time between the updates - but no luck.
package de.leo.android.buddytracker_lib
import android.content.Context
import android.location.*
import android.os.Looper
import android.util.Log
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
private const val MOCK_PROVIDER = "MockLocationProvider"
private const val LOG_TAG ="**** Test ****"
class LocationHandlerAndroidTests : LocationListener {
private lateinit var context: Context
private lateinit var locationManager: LocationManager
private var locationUpdateCount = 0
private var currentLocation: Location? = null
override fun onLocationChanged(location: Location) {
locationUpdateCount++
currentLocation = location
}
@Before
fun init() {
context = InstrumentationRegistry.getInstrumentation().context
locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
locationManager.addTestProvider(
MOCK_PROVIDER,
false,
false,
false,
false,
false,
false,
false,
Criteria.POWER_LOW,
Criteria.ACCURACY_FINE
)
locationManager.setTestProviderEnabled(MOCK_PROVIDER, true)
assertTrue(locationManager.isLocationEnabled)
locationUpdateCount = 0
currentLocation = null
Thread.sleep(5000L)
}
@After
fun tearDown() {
locationManager.removeTestProvider(MOCK_PROVIDER)
}
@Test
fun requestLocationUpdatesTest() {
Log.d(LOG_TAG, "Requesting Location Updates")
locationManager.requestLocationUpdates(MOCK_PROVIDER, 4000, 10.0f, this, Looper.getMainLooper())
val location1 = Location(MOCK_PROVIDER)
location1.latitude = 10.0
location1.longitude = 20.0
location1.accuracy = 2.0f
location1.time = 1000
location1.elapsedRealtimeNanos = 10000000000
Log.d(LOG_TAG, "set location 1")
locationManager.setTestProviderLocation(MOCK_PROVIDER, location1)
Thread.sleep(5000L)
val location2 = Location(MOCK_PROVIDER)
location2.latitude = 11.0
location2.longitude = 21.0
location2.accuracy = 2.0f
location2.time = 5000
location2.elapsedRealtimeNanos = 15000000000
Log.d(LOG_TAG, "set location 2")
locationManager.setTestProviderLocation(MOCK_PROVIDER, location2)
Thread.sleep(5000L)
// Check if your listener reacted the right way
assertEquals("Got location updates", 2, locationUpdateCount)
assertEquals(11.0, currentLocation?.latitude)
assertEquals(21.0, currentLocation?.longitude)
}
}
Any tips what I made wrong here?