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.
}
I solve this problem like this:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With