Unregister network callback in tearDown
Representing networkCallback as a non-null lateinit var and using
property isInitialized seems more appropriate than making
networkCallback nullable. Making networkCallback nullable would require
null checks / safe calls for every use. However, from the tests'
perspective networkCallback cannot be null; the only concern is
tearDown() which has to deal with early exits from setUp() due to
assumption / assertion failures and therefore partially initialized
state.
networkCallback can only be initialized when requestNetwork() is called
as unregisterNetworkCallback() will throw an exception if the callback
was never registered.
Test: TH
Change-Id: I2aad7d781e6955b29d505e670181209c33db7680
diff --git a/tests/cts/net/src/android/net/cts/ApfIntegrationTest.kt b/tests/cts/net/src/android/net/cts/ApfIntegrationTest.kt
index 98926ea..ad7163d 100644
--- a/tests/cts/net/src/android/net/cts/ApfIntegrationTest.kt
+++ b/tests/cts/net/src/android/net/cts/ApfIntegrationTest.kt
@@ -33,6 +33,7 @@
import com.google.common.truth.Truth.assertThat
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
+import org.junit.After
import org.junit.Assume.assumeTrue
import org.junit.Before
import org.junit.Test
@@ -49,25 +50,34 @@
private val cm by lazy { context.getSystemService(ConnectivityManager::class.java)!! }
private val pm by lazy { context.packageManager }
private lateinit var wifiIfaceName: String
+ private lateinit var networkCallback: TestableNetworkCallback
+
@Before
fun setUp() {
assumeTrue(pm.hasSystemFeature(FEATURE_WIFI))
assumeTrue(isVendorApiLevelNewerThan(Build.VERSION_CODES.TIRAMISU))
- val cb = TestableNetworkCallback()
+ networkCallback = TestableNetworkCallback()
cm.requestNetwork(
NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build(),
- cb
+ networkCallback
)
- cb.eventuallyExpect<LinkPropertiesChanged>(TIMEOUT_MS) {
+ networkCallback.eventuallyExpect<LinkPropertiesChanged>(TIMEOUT_MS) {
wifiIfaceName = assertNotNull(it.lp.interfaceName)
true
}
assertNotNull(wifiIfaceName)
}
+ @After
+ fun tearDown() {
+ if (::networkCallback.isInitialized) {
+ cm.unregisterNetworkCallback(networkCallback)
+ }
+ }
+
@Test
fun testGetApfCapabilities() {
val capabilities = SystemUtil