1

I am trying to test some LiveData in a Viewmodel

I have mocked both LifecycleOwner and LifecycleRegistry

My test method below:

@Test
public void testLifecycle(){
    assertThat(viewModel.user().hasObservers(), is(false));

    Observer<FirebaseUser> firebaseUserObserver = (Observer<FirebaseUser>)mock(Observer.class);
    viewModel.user().observe(lifecycleOwner, firebaseUserObserver);

    assertThat(viewModel.user().hasObservers(), is(true));

    lifecycleRegistry.setCurrentState(Lifecycle.State.RESUMED);    
    assertThat(viewModel.user().hasActiveObservers(),is(true));    //assertion failure

    lifecycleRegistry.setCurrentState(Lifecycle.State.DESTROYED);
    assertThat(viewModel.user().hasActiveObservers(), is(false));
}

When I run this method I get a assertion failure at:

assertThat(viewModel.user().hasActiveObservers(),is(true));    

I don't understand why this fails. hasActiveObservers() should return true if LiveData has at least one observer whose lifecycle is Lifecycle.State.STARTED or Lifecycle.State.RESUMED state (this means state is active).

Have I missed something here?

CJR
  • 3,174
  • 6
  • 34
  • 78
  • If you've mocked the `LifecycleRegistry`, then `setCurrentState()` doesn't call into the actual implemention. Why are you mocking `LifecycleRegistry` at all? – ianhanniballake Jun 05 '19 at 16:32
  • @ianhanniballake Makes sense, you are correct. Should I only mock the LifecycleOwner and create lifecycleregistry as usual? Is that what you should do to test Viewmodel Livedata? – CJR Jun 05 '19 at 17:09
  • If you want the real behavior of `LifecycleRegistry`, then you should create a real `LifecycleRegistry` object. – ianhanniballake Jun 05 '19 at 17:17
  • Okay, I see. Testing runs as it should, thanks for the help. If you want, you could reply the first comment as an aswer so I can accept for any future viewers. – CJR Jun 05 '19 at 17:29

1 Answers1

2

If you've mocked the LifecycleRegistry, then setCurrentState() doesn't call into the actual implementation. If you want the real behavior of LifecycleRegistry (i.e., actually changing the state to an active state), then you should create a real LifecycleRegistry object.

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
  • Please look into this question I tried to solve it but could not solve it https://stackoverflow.com/questions/56513672/errorunable-to-resolve-dependency-for-appdebugandroidtest-compileclasspath @ianhanniballake – Pie Jun 09 '19 at 14:53