gpt4 book ai didi

android - 是否可以禁用 toast 或等到 toast 在测试时消失

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:46:36 44 4
gpt4 key购买 nike

我正在使用 Espresso 测试一个应用程序。我有一个问题,是否可以等到当前没有 toast 显示。我的应用程序中有很多不同的 toast,但是在测试时我遇到了问题,因为据我所知,焦点已经转移到 toast 上,并且我得到了完全不同的 View 层次结构,正如我在错误日志中看到的那样。
所以我的问题是可以隐藏所有(具有 root 访问权限的系统范围)或者只是等到屏幕上有任何 toast 或者是否可以手动将焦点设置到 Activity View 层次结构。
如果您对此问题有任何帮助,我将不胜感激。
谢谢。

附言直接在我的应用程序中的某处禁用 toast 不是一种选择,因为它会为应用程序带来一些额外的逻辑,而这些逻辑仅在测试时才需要。

最佳答案

您可以使用自定义空闲资源让 Espresso 等到所有 toast 都消失。

我在这里使用 CountingIdlingResource,这是一个管理计数器的空闲资源:当计数器从非零变为零时,它会通知转换回调。

Here是一个完整的例子;关键点如下:

public final class ToastManager {
private static final CountingIdlingResource idlingResource = new CountingIdlingResource("toast");
private static final View.OnAttachStateChangeListener listener = new View.OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(final View v) {
idlingResource.increment();
}

@Override
public void onViewDetachedFromWindow(final View v) {
idlingResource.decrement();
}
};

private ToastManager() { }

public static Toast makeText(final Context context, final CharSequence text, final int duration) {
Toast t = Toast.makeText(context, text, duration);
t.getView().addOnAttachStateChangeListener(listener);
return t;
}

// For testing
public static IdlingResource getIdlingResource() {
return idlingResource;
}
}

如何显示 toast :

ToastManager.makeText(this, "Third", Toast.LENGTH_SHORT).show();

如何设置/拆除测试:

@Before
public void setUp() throws Exception {
super.setUp();
injectInstrumentation(InstrumentationRegistry.getInstrumentation());
Espresso.registerIdlingResources(ToastManager.getIdlingResource());
getActivity();
}

@After
public void tearDown() throws Exception {
super.tearDown();
Espresso.unregisterIdlingResources(ToastManager.getIdlingResource());
}

关于android - 是否可以禁用 toast 或等到 toast 在测试时消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31998205/

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