模拟撰写 UI 上的用户交互

问题描述 投票:0回答:1

我试图了解如何测试用 Jetpack Compose 编写的 Android UI。切换到 Compose 时,我的假设是我能够启动应用程序并模拟用户交互(例如按钮单击),就像使用 Espresso 处理基于 XML 的布局一样。

根据我所读到的内容,Compose 测试 API 依赖于在测试中实例化可组合项,而不是简单地允许我运行应用程序并模拟用户交互。

有什么方法可以使用我的应用程序进行 Espresso 风格的 UI 测试,或者使用 Compose 时是否不支持此功能?

android android-jetpack-compose android-jetpack
1个回答
0
投票

如果您谈论的是记录测试,据我所知,Jetpack Compose 中尚不存在这种功能。但是,您仍然可以使用常规 Jetpack Compose 测试来测试跨多个屏幕的交互。

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            RootComposable()
        }
    }
}

@Composable
fun RootComposable() {
    //...
}

为顶级可组合项创建测试,然后以编程方式模拟整个应用程序的用户交互。您还可以使用活动引用来访问测试中的字符串资源。

class RootComposableTest {

    @get:Rule
    val testRule = createAndroidComposeRule<MainActivity>()


    @Test
    fun rootComposable_showsTitle() {
        val screenTitle = testRule.activity.getString("main_activity_title")

        testRule.activity.setContent {
            RootComposable()
        }
        testRule.onNodeWithText(screenTitle).assertExists()
    }

    @Test
    fun rootComposable_onClick_navigateToNextScreen() {
        val nextButtonText = testRule.activity.getString("btn_next_screen")
        val nextScreenTitle = testRule.activity.getString("title_next_screen")
        val nextNextButtonText = testRule.activity.getString("btn_next_next_screen")
        val nextNextScreenTitle = testRule.activity.getString("title_next_next_screen")

        testRule.activity.setContent {
            RootComposable()
        }

        testRule.onNodeWithText(nextButtonText).performClick()
        testRule.waitUntil(1000) { testRule.onNodeWithText(nextScreenTitle).assertExists()}
        testRule.onNodeWithText(nextNextButtonText).performClick()
        testRule.waitUntil(1000) { testRule.onNodeWithText(nextNextScreenTitle).assertExists()}
    }

}

但是,Compose 测试强烈鼓励编写小型模块化测试,即使理论上您可以在一次测试中测试整个应用程序。我发现为每个屏幕级 Composable 创建单独的测试类很有用,然后为 Composable 作为函数输入的每个参数组合创建一个测试。

© www.soinside.com 2019 - 2024. All rights reserved.