Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test SingleLiveEvent<Void> variable?

I have a SingleLiveEvent<Void> variable. On getting response from api I am making it post. My callback is called and a popup is shown. My question is how will I write a test case for checking, is my popup shown or not.

Live Event:

private SingleLiveEvent<Void> onAccountOverDrawn = new SingleLiveEvent<>();

On success response I am calling:

onAccountOverDrawn.post();

In my fragment I am registering it as

viewModel.getOnAccountOverDrawn().observe(this, aVoid -> onAccountOverDrawn());

and in onAccountOverDrawn() I am just showing a popup.

So how will I write a test case for this scenario?

Current test case:

@Test
public void updateApplicationStatus_AccountOverdrawn() {
    viewModel.updateApplicationStatus("AMOUNT_PENDING");

    assertNotNull(viewModel.getOnAccountOverDrawn()); //this line is of no use. Need to change this.
}
like image 653
Ashwani Kumar Avatar asked Nov 26 '22 00:11

Ashwani Kumar


1 Answers

I solve this problem like this:

  1. Get LiveData and subscribe our mock-observer to it.
  2. Call the method that should change the LiveData inside the ViewModel.
  3. Check that our mock-observer received the updated data.
  4. Check that there were no more changes of this mock-observer.
  5. Check that if we re-subscribe this mock-observer on the same LiveData then we do not receive data

See code below:

@RunWith(MockitoJUnitRunner.class)
public class SomeFeatureViewModelTest {

    private SomeFeatureViewModel mSomeFeatureViewModel;

    // Rule for help testing. Just trust me you need it :)
    @Rule
    public InstantTaskExecutorRule mRule = new InstantTaskExecutorRule();

    @Mock
    private Observer<Void> mOnClickButtonEventObserver;

    @Before
    public void setup() {
        mSomeFeatureViewModel = new SomeFeatureViewModel();
    }

    @Test
    public void clickOnNextScreenButton() {

        // get LiveData and subscribe our observer to it:
        mSomeFeatureViewModel.getOnClickButtonEvent().observeForever(mOnClickButtonEventObserver);

        // call the method that should change the LiveData inside the ViewModel:
        mSomeFeatureViewModel.clickOnNextScreenButton();

        // check that our observer received the updated data:
        verify(mOnClickButtonEventObserver).onChanged(null);

        // check that there were no more changes of this observer:
        verifyNoMoreInteractions(mOnClickButtonEventObserver);

        // check that if we re-subscribe this observer on the same LiveData then we do not receive data:
        mSomeFeatureViewModel.getOnClickButtonEvent().observeForever(mOnClickButtonEventObserver);
        verifyNoMoreInteractions(mOnClickButtonEventObserver);

    }

}
like image 113
Jack Avatar answered Nov 28 '22 12:11

Jack