Issue#67 Extract OkHttp IdlingResources into a separate module

This commit is contained in:
Gergely Hegedus 2022-05-27 16:38:14 +03:00
parent bbe077dde8
commit 756c74e174
9 changed files with 26 additions and 21 deletions

View file

@ -0,0 +1,19 @@
package org.fnives.test.showcase.android.testutil.synchronization.idlingresources
class CompositeDisposable(disposable: List<Disposable> = emptyList()) : Disposable {
constructor(vararg disposables: Disposable) : this(disposables.toList())
private val disposables = disposable.toMutableList()
override val isDisposed: Boolean get() = disposables.all(Disposable::isDisposed)
fun add(disposable: Disposable) {
disposables.add(disposable)
}
override fun dispose() {
disposables.forEach {
it.dispose()
}
}
}

View file

@ -0,0 +1,6 @@
package org.fnives.test.showcase.android.testutil.synchronization.idlingresources
interface Disposable {
val isDisposed: Boolean
fun dispose()
}

View file

@ -0,0 +1,19 @@
package org.fnives.test.showcase.android.testutil.synchronization.idlingresources
import androidx.test.espresso.IdlingRegistry
import androidx.test.espresso.IdlingResource
class IdlingResourceDisposable(private val idlingResource: IdlingResource) : Disposable {
override var isDisposed: Boolean = false
private set
init {
IdlingRegistry.getInstance().register(idlingResource)
}
override fun dispose() {
if (isDisposed) return
isDisposed = true
IdlingRegistry.getInstance().unregister(idlingResource)
}
}

View file

@ -0,0 +1,50 @@
package org.fnives.test.showcase.android.testutil.synchronization.idlingresources
import androidx.annotation.CheckResult
import androidx.annotation.NonNull
import androidx.test.espresso.IdlingResource
import okhttp3.Dispatcher
import okhttp3.OkHttpClient
/**
* AndroidX version of Jake Wharton's OkHttp3IdlingResource.
*
* Reference: https://github.com/JakeWharton/okhttp-idling-resource/blob/master/src/main/java/com/jakewharton/espresso/OkHttp3IdlingResource.java
*/
class OkHttp3IdlingResource private constructor(
private val name: String,
private val dispatcher: Dispatcher
) : IdlingResource {
@Volatile
var callback: IdlingResource.ResourceCallback? = null
init {
val currentCallback = dispatcher.idleCallback
dispatcher.idleCallback = Runnable {
callback?.onTransitionToIdle()
currentCallback?.run()
}
}
override fun getName(): String = name
override fun isIdleNow(): Boolean = dispatcher.runningCallsCount() == 0
override fun registerIdleTransitionCallback(callback: IdlingResource.ResourceCallback?) {
this.callback = callback
}
companion object {
/**
* Create a new [IdlingResource] from `client` as `name`. You must register
* this instance using `Espresso.registerIdlingResources`.
*/
@CheckResult
@NonNull
fun create(@NonNull name: String?, @NonNull client: OkHttpClient?): OkHttp3IdlingResource {
if (name == null) throw NullPointerException("name == null")
if (client == null) throw NullPointerException("client == null")
return OkHttp3IdlingResource(name, client.dispatcher)
}
}
}