You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅针对点击元素至页面加载流程生成Baseline Profile?

解决方案

要生成仅涵盖「点击列表元素到对应页面加载」阶段的Baseline Profile,核心是手动控制Profile的收集范围,避免将应用启动流程包含进去。BaselineProfileRule提供了profile()函数,用来包裹需要生成Profile的代码段,具体实现如下:

修改后的代码示例

import androidx.benchmark.macro.ExperimentalBaselineProfilesApi
import androidx.benchmark.macro.junit4.BaselineProfileRule
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import androidx.test.uiautomator.By
import androidx.test.uiautomator.Until
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

@OptIn(ExperimentalBaselineProfilesApi::class)
@RunWith(AndroidJUnit4ClassRunner::class)
class BaselineProfileGenerator {

    @get:Rule
    val rule = BaselineProfileRule()

    // 生成仅包含启动到首页加载的Profile(可选)
    @Test
    fun generateStartupProfile() = rule.collectBaselineProfile(
        packageName = "com.bowerydigital.bend"
    ) {
        startActivityAndWait()
        // 等待首页完全加载完成
        device.wait(Until.hasObject(By.text("Wake Up")), 30_000)
    }

    // 生成仅包含点击元素到目标页面加载的Profile
    @Test
    fun generateClickToPageProfile() = rule.collectBaselineProfile(
        packageName = "com.bowerydigital.bend"
    ) {
        // 先完成应用启动和首页加载,这部分不生成Profile
        startActivityAndWait()
        device.wait(Until.hasObject(By.text("Wake Up")), 30_000)

        // 仅对包裹在profile{}内的代码生成Profile
        profile {
            device.findObject(By.text("Wake Up")).click()
            // 等待目标页面加载完成,替换为你页面的特征元素
            device.wait(Until.hasObject(By.text("目标页面标识文本")), 30_000)
        }
    }
}

关键说明

  1. 为什么@Before注解无效?
    collectBaselineProfile内部会自动重启应用以保证测试环境的一致性,因此@Before中执行的启动操作会被覆盖,无法达到预先启动应用的目的。

  2. profile()函数的作用
    profile()是MacroScope提供的方法,仅会收集该函数内部代码执行过程中的热点路径,从而精准控制Profile的生成范围。

  3. 注意事项

    • 务必在profile()块内等待目标页面加载完成,确保覆盖完整的页面渲染流程;
    • 如果需要同时生成启动阶段和点击阶段的Profile,可保留两个测试方法分别执行。

内容的提问来源于stack exchange,提问作者Mattia Ferigutti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 19:05:22