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

如何在Espresso中检测Android应用的屏幕方向?(Kotlin)

如何在Espresso(Kotlin)中验证屏幕是否为竖屏模式

你代码里的resources无法识别,是因为UI测试类不能直接访问Android的Resources对象,得通过测试框架提供的工具类来获取设备/应用的配置信息。下面是两种可行的实现方式:

方式一:使用InstrumentationRegistry(兼容场景)

通过InstrumentationRegistry获取应用上下文,进而读取屏幕配置:

import android.content.res.Configuration
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Test

class ScreenOrientationTest {

    @Test
    fun isOrientationVertical() {
        val appContext = InstrumentationRegistry.getInstrumentation().targetContext
        val currentOrientation = appContext.resources.configuration.orientation
        
        // 断言当前为竖屏(ORIENTATION_PORTRAIT)
        assertEquals("屏幕未处于竖屏模式", Configuration.ORIENTATION_PORTRAIT, currentOrientation)
    }
}

注意:你之前的代码错误地用了ORIENTATION_LANDSCAPE(横屏)做断言,这里修正为ORIENTATION_PORTRAIT。

方式二:使用ActivityScenario(推荐,基于AndroidX测试库)

如果你的测试绑定了具体Activity,用ActivityScenario获取Activity实例后读取配置更贴近实际运行场景:

import android.content.res.Configuration
import androidx.test.core.app.ActivityScenario
import org.junit.Assert.assertEquals
import org.junit.Test

class MainActivityOrientationTest {

    @Test
    fun isOrientationVertical() {
        val scenario = ActivityScenario.launch(MainActivity::class.java)
        
        scenario.onActivity { activity ->
            val currentOrientation = activity.resources.configuration.orientation
            assertEquals(Configuration.ORIENTATION_PORTRAIT, currentOrientation)
        }
    }
}

额外说明

  • 确保测试模块依赖了必要的AndroidX库,比如在build.gradle中添加:
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
androidTestImplementation 'androidx.test.ext:junit-ktx:1.1.5'
  • 若为多模块项目,targetContext会指向你测试的应用模块上下文,确保路径正确。

内容的提问来源于stack exchange,提问作者Manika Sharma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 07:55:16