Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 716
gokhan Avatar asked Jun 29 '18 09:06

gokhan


People also ask

How do you write JUnit test cases for Android?

You write your local unit test class as a JUnit 4 test class. To do so, create a class that contains one or more test methods, usually in module-name/src/test/ . A test method begins with the @Test annotation and contains the code to exercise and verify a single aspect of the component that you want to test.

How do you write unit testing activities?

To test an activity, you use the ActivityTestRule class provided by the Android Testing Support Library. This rule provides functional testing of a single activity. The activity under test will be launched before each test annotated with @Test and before any method annotated with @Before.


1 Answers

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.

like image 180
Raz Avatar answered Nov 02 '22 12:11

Raz