3

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.

Abhas Arya
  • 470
  • 1
  • 5
  • 19

2 Answers2

4

There is a TestLifecycleOwner, which probably does what you want.

https://cs.android.com/androidx/platform/frameworks/support/+/androidx-master-dev:lifecycle/lifecycle-runtime-testing/src/main/java/androidx/lifecycle/testing/TestLifecycleOwner.kt;l=38

It's part of the androidx.lifecycle:lifecycle-runtime-testing artifact.

dlam
  • 3,547
  • 17
  • 20
  • 1
    Thank you!! This is exactly what I was looking for - had no idea this existed. This S.O. post also walks through how to properly mock the TestLifecycleOwner you mentioned above, manually: https://stackoverflow.com/questions/51099003/how-can-i-add-unit-test-for-android-architecture-components-life-cycle-event I was able to successfully mock lifecycle events with the TestLifecycleOwner's LifecycleRegistry – Abhas Arya Jul 01 '20 at 17:50
3

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)
Abhas Arya
  • 470
  • 1
  • 5
  • 19