我有一个SingleLiveEvent<Void>
变量。从api获得响应后,我将其发布。我的回调被调用,并显示一个弹出窗口。
我的问题是如何编写测试用例进行检查,是否显示弹出窗口。
现场活动:
private SingleLiveEvent<Void> onAccountOverDrawn = new SingleLiveEvent<>();
成功响应时,我打电话给:
onAccountOverDrawn.post();
在我的片段中,我将其注册为
viewModel.getOnAccountOverDrawn().observe(this, aVoid -> onAccountOverDrawn());
,在onAccountOverDrawn()
中,我只是显示一个弹出窗口。
那么我将如何为这种情况编写一个测试用例?
当前测试用例:
@Test
public void updateApplicationStatus_AccountOverdrawn() {
viewModel.updateApplicationStatus("AMOUNT_PENDING");
assertNotNull(viewModel.getOnAccountOverDrawn()); //this line is of no use. Need to change this.
}
答案 0 :(得分:0)
如果要测试是否有弹出窗口,可以使用Robolectric。
答案 1 :(得分:0)
如果要测试是否已观察到实时数据,可以使用以下测试
private LifecycleOwner lifecycleOwner;
MutableLiveData<Boolean> mutableLiveData = new MutableLiveData(); //Live data to be observed from viewModel
@Mock
private Lifecycle lifecycle;
@Before
public void setup() {
lifecycleOwner = getLifecycleOwner();
PowerMockito.when(lifecycle.getCurrentState()).thenReturn(Lifecycle.State.CREATED);
}
@Test
public void test() {
mutableLiveData.observe(lifecycleOwner, new Observer<Boolean>() {
@Override
public void onChanged(@Nullable Boolean aBoolean) {
assertTrue(aBoolean);
}
});
mutableLiveData.postValue(true);
}
private LifecycleOwner getLifecycleOwner() {
return new LifecycleOwner() {
@NonNull
@Override
public Lifecycle getLifecycle() {
return lifecycle;
}
};
}
答案 2 :(得分:0)
我这样解决这个问题:
请参见下面的代码:
@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);
}
}