How to mock Android's ProcessLifecycleOwner

Viewed 1333

I am working on a utility class that subscribes to the app going foreground/background via ProcessLifecycleOwner api. The class takes in a ProcessLifecycleOwner instance, and has the following methods which observe on lifecycle events:

@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun startSomething() {
    appStatusSubject.onNext(AppStatus.FOREGROUNDED)
}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stopSomething() {
    appStatusSubject.onNext(AppStatus.BACKGROUNDED)
}

I would like to write a unit test for this utility class. Is there anyway I can mock the ProcessLifecycleOwner object, have it emit certain lifecycle events, and assert that appStatusSubject.onNext(...) is called?

Would really appreciate any advice.

2 Answers

If you want to create a super simple fake for the LifecycleOwner, you can do so as follows:

class TestLifecycleOwner() : LifecycleOwner {

    private val registry = LifecycleRegistry(this).apply {
        currentState = Lifecycle.State.RESUMED
    }

    override fun getLifecycle(): Lifecycle = registry
}

Then you can simply call:

testLifecycleOwner.lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
Related