如何解决Android,在检测模式下运行常规应用仅限 adb + 调试
我希望以一种可以在运行时访问 InstrumentationRegistry.getInstrumentation()
的方式运行 Android 应用。
这仅用于调试版本,通过 ADB 安装应用程序就足够了。因为我不想使用仪器测试套件,所以我不想使用 InstrumentationTestRunner
,而是直接启动应用程序的 MainActivity
。
这怎么可能?
我尝试过的:
- 添加了对测试包的常规实现依赖(而不是仅测试依赖) - 有效
implementation 'androidx.test.uiautomator:uiautomator:2.2.0'
implementation 'androidx.test:runner:1.1.0'
- 向清单添加了检测
<instrumentation android:name=".MainActivity"
android:targetPackage="com.android.shell"
android:label="App" />
(不确定这是否真的正确。)
- 使用(设备上已安装的应用)运行应用
adb shell am instrument -w com.example.app/.MainActivity
结果:
android.util.AndroidException: INSTRUMENTATION_Failed: com.example.app/com.example.app.MainActivity
at com.android.commands.am.Instrument.run(Instrument.java:519)
at com.android.commands.am.Am.runInstrument(Am.java:202)
at com.android.commands.am.Am.onRun(Am.java:80)
at com.android.internal.os.BaseCommand.run(BaseCommand.java:60)
at com.android.commands.am.Am.main(Am.java:50)
at com.android.internal.os.RuntimeInit.nativeFinishInit(Native Method)
at com.android.internal.os.RuntimeInit.main(RuntimeInit.java:399)
所以本质上我的问题是,我如何以可以在运行时使用 UiAutomator
的方式运行应用程序?
提前致谢!
解决方法
是的,这是可能的:
1. 将依赖项添加到您的 build.gradle。应该是这样的:
implementation 'androidx.test.ext:junit:1.1.2'
implementation 'androidx.test.uiautomator:uiautomator:2.2.0'
implementation 'androidx.test:runner:1.1.0'
2. 在您的 application
标记内和 instrumentation 内添加以下 uses-library AndroidManifest.xml:
manifest
将 <!-- Add inside application tag -->
<uses-library android:name="android.test.runner" />
设置为您自己的应用程序包名称。
android:targetPackage
3. 创建您的活动。您可以在那里使用 <!-- Add inside manifest tag -->
<instrumentation
android:name="androidx.test.runner.AndroidJUnitRunner"
android:label="App"
android:targetPackage="com.example.app" />
</manifest>
。
4. 在应用程序类的相同源集中创建测试类(在 src/main/java 内)
InstrumentationRegistry.getInstrumentation();
5. 构建并安装应用。
6. 运行应用程序: @RunWith(AndroidJUnit4.class)
public class Test {
@org.junit.Test
public void test() {
// Put any code here. It is launching the activity.
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
Context context = instrumentation.getTargetContext();
Intent intent = new Intent(context,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
7.(可选)如果您想直接从 Android Studio 中的 adb shell am instrument -w -m -e debug false -e class 'com.example.app.Test' com.example.app/androidx.test.runner.AndroidJUnitRunner
按钮执行它,请将它添加到您的 run
中的 android
中,它会改变必须创建测试类的地方,指向与主代码相同的文件夹:
build.gradle
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。