How can I add unit test for android architecture components life cycle event?

gokhan picture gokhan · Jun 29, 2018 · Viewed 8.3k times · Source

I tried to add a unit test for my function which supports architecture components lifecycle event. To support lifecycle event, I added the @OnLifecycleEvent annotation for my function which I want to do something when that event occurred.

Everything is working as expected but I want to create a unit test for that function to check my function running when the intended event occurred.

 public class CarServiceProvider implements LifecycleObserver {

    public void bindToLifeCycle(LifecycleOwner lifecycleOwner) {
        lifecycleOwner.getLifecycle().addObserver(this);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onClear() {
       Log.i("CarServiceProvider", "onClear called");
    }
 }

I tried to mock LifecycleOwner and create new LifecycleRegistery to change the state of lifecycle observer but I didn't do.

How can I test my onClear() function called when state changed ?

Answer

Raz picture Raz · Oct 15, 2018

You should be able to use the LifecycleRegistry

Your test would do something like below:

@Test
public void testSomething() {
  LifecycleRegistry lifecycle = new LifecycleRegistry(mock(LifecycleOwner.class));

  // Instantiate your class to test
  CarServiceProvider carServiceProvider = new CarServiceProvider();
  carServiceProvider.bindToLifeCycle(lifecycle);

  // Set lifecycle state
  lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_STOP)

  // Verify that the ON_STOP event was handled, with an assert or similar check
  ...
}

If you are testing Lifecycle.Event.ON_DESTROY then you probably need to call handleLifecycleEvent(Lifecycle.Event.ON_CREATE) prior to this.