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

Espresso测试报错No instrumentation registered! 相机权限自动授予问题求助

解决Espresso测试中"No instrumentation registered!"错误并自动授予相机权限

这个错误的核心原因是你混合使用了旧的Android Support测试库和新的AndroidX测试库,导致测试环境的Instrumentation无法正确注册,同时你的依赖中还有重复引入的问题,进一步干扰了测试初始化。下面是具体的修复方案:

1. 统一测试依赖为AndroidX版本

首先清理你的build.gradle依赖,移除旧的Support库测试规则,替换为AndroidX版本,同时删掉重复的依赖:

dependencies {
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    
    testImplementation 'junit:junit:4.13.2'
    
    // 统一使用AndroidX测试库
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.ext:junit-ktx:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
    androidTestImplementation 'androidx.test:runner:1.5.2'
    // AndroidX版本的权限规则库,替代旧的support版本
    androidTestImplementation 'androidx.test:rules:1.5.0'
}

2. 修正测试类的Rule导入与初始化

确保你的测试类中使用的是AndroidX版本的GrantPermissionRule和ActivityScenarioRule,同时修正ActivityScenarioRule的初始化写法:

import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.rule.GrantPermissionRule
import android.Manifest
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class MainActivityTest {

    @get:Rule
    var activityScenarioRule = ActivityScenarioRule(MainActivity::class.java)

    @get:Rule
    val permissionRule = GrantPermissionRule.grant(
        Manifest.permission.CAMERA
    )

    @Test
    fun checkName(){
        onView(withId(R.id.etName)).perform(typeText("Alex"))
        onView(withId(R.id.btSend)).perform(click())
        onView(withId(R.id.tvName)).check(matches(isDisplayed()))
        onView(withId(R.id.tvName)).check(matches(withText("Alex")))
    }
}

3. 确认测试运行器配置

在build.gradle的android.defaultConfig中,确保指定了AndroidX的测试运行器:

android {
    defaultConfig {
        // 其他配置...
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
}

完成以上修改后,重新同步项目并运行测试,应该就能正常启动MainActivity并自动授予相机权限,不会再出现Instrumentation未注册的错误了。

内容的提问来源于stack exchange,提问作者Alex Danilov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 10:31:14