gpt4 book ai didi

android - 如何测试 SingleLiveEvent 变量?

转载 作者:行者123 更新时间:2023-11-28 20:13:12 24 4
gpt4 key购买 nike

我有一个 SingleLiveEvent<Void>多变的。从 api 获得响应后,我将其发布。我的回调被调用并显示一个弹出窗口。我的问题是我将如何编写测试用例来检查我的弹出窗口是否显示。

现场 Activity :

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

成功响应我打电话:

onAccountOverDrawn.post();

在我的 fragment 中,我将其注册为

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.
}

最佳答案

我这样解决这个问题:

  1. 获取 LiveData 并为我们的模拟观察者订阅它。
  2. 调用应更改 ViewModel 内的 LiveData 的方法。
  3. 检查我们的模拟观察者是否收到了更新的数据。
  4. 检查这个模拟观察者没有更多变化。
  5. 检查如果我们在同一个 LiveData 上重新订阅这个模拟观察者,那么我们不会收到数据

见下面的代码:

@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);

}

}

关于android - 如何测试 SingleLiveEvent<Void> 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55021261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com