Search code examples
androidandroid-testingandroid-architecture-componentsandroid-architecture-lifecycle

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


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 ?


Solution

  • Despite of I am not a big fan, I would go with Robolectric making use of ActivityController to achieve this.

    Given the fact that the "Observables" of the Observer pattern applied in Android Lifecycle workflow are Activities, Fragments... An application context is a must and we need somehow bring it to our test scenario.

    I achieved the expected result by doing this

    build.gradle

    testCompile "org.robolectric:robolectric:3.5.1"
    

    CarServiceProviderTest.java

    @RunWith(RobolectricTestRunner.class)
    @Config(constants = BuildConfig.class)
    public class CarServiceProviderTest {
    
        @Test
        public void shouldFireOnClear(){
    
            //Grab the Activity controller
            ActivityController controller = Robolectric.buildActivity(JustTestActivity.class).create().start();
            AppCompatActivity activity = (AppCompatActivity) controller.get();
    
            //Instanciate our Observer
            CarServiceProvider carServiceProvider = new CarServiceProvider();
            carServiceProvider.bindToLifeCycle(activity);
    
            //Fire the expected event
            controller.stop();
    
            //Assert
            Assert.assertTrue(carServiceProvider.wasFired);
        }
    }
    

    CarServiceProvider.java

    public class CarServiceProvider implements LifecycleObserver {
    
        public boolean wasFired;
    
        public void bindToLifeCycle(LifecycleOwner lifecycleOwner) {
            lifecycleOwner.getLifecycle().addObserver(this);
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        public void onClear() {
            wasFired = true;
        }
    }