是否可以禁用吐司或等到吐司在测试时消失

Is it possible to disable Toasts or wait until toast disappears while testing

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

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

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

这里我使用 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;
    }
}

吐司的显示方式:

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

如何set-up/tear-down测试:

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

我还没有找到任何完美的解决方案,但最好的办法是让一个 mToast 成员变量可见以供测试,并用它来取消 @After 中任何活动的 toast,就像这样:

显示吐司时(测试中Activity的生产代码):

@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
Toast mToast;

private void showToast(final String text) {
    mToast = Toast.makeText(this, text, Toast.LENGTH_LONG);
    mToast.show();
}

测试代码(与被测代码在同一个包中):

    @After
    public void tearDown() {
        // Remove any toast message that is still shown:
        Toast toast = mActivityRule.getActivity().mToast;
        if (toast != null) {
            toast.cancel();
        }
    }

要求您稍微更改生产代码,但在最新版本的Android Studio中使用@VisibleForTesting会报错如果你在其他地方使用了成员变量。