如何与 ActivityInstrumentationTestCase2 中的 UI 组件交互?

How do I interact with UI Components from within ActivityInstrumentationTestCase2?

我正在尝试学习如何为 Android 编写仪器测试。我有一个 class 扩展 ActivityInstrumentationTestCase2 以测试我的 Activity。在我的一项测试中,我尝试执行以下操作:

Button button = (Button) getActivity().findViewById(R.id.my_button);
button.performClick() // this method throws CalledFromWrongThreadException

从周围阅读听起来我不能以这种方式与 UI 组件交互 - 我必须创建一个新的 运行nable 和 运行 它在 UI 线程 (Testing with UI elements in Android view) or run the whole test on the UI thread using @UiThreadTest (Android: Only the original thread that created a view hierarchy can touch its views - UnitTest)。然而,前者的解决方案非常麻烦,而后者对我来说根本不起作用(抛出相同的异常)。

我想要的是能够直接与按钮交互,因为 testing fundamentals documentation 似乎暗示这是可能的(至少对于 Spinner)。这是可能的还是我必须像第一个 link 建议的那样担心 运行 在不同的线程上宁?

正如 Muhammed Babar 在评论中所解释的那样,我需要使用 TouchUtils.clickView()