Android,在检测模式下运行常规应用程序(仅限 adb + debug)

Nor*_*ert 5 android android-testing android-instrumentation android-uiautomator

我想以一种可以InstrumentationRegistry.getInstrumentation()在运行时访问的方式运行 Android 应用程序。

这仅适用于调试版本,通过 ADB 安装应用程序就足够了。因为我不想使用仪器测试套件,所以我不想使用InstrumentationTestRunner但直接启动MainActivity应用程序。

这怎么可能?

我尝试过的:

  1. 添加了对测试包的常规实现依赖(而不是仅测试依赖) - 有效
    implementation 'androidx.test.uiautomator:uiautomator:2.2.0'
    implementation 'androidx.test:runner:1.1.0'
Run Code Online (Sandbox Code Playgroud)
  1. 添加了检测清单
    <instrumentation android:name=".MainActivity"
        android:targetPackage="com.android.shell"
        android:label="App" />
Run Code Online (Sandbox Code Playgroud)

(不确定这是否真的正确。)

  1. 使用运行应用程序(应用程序已安装在设备上)
adb shell am instrument -w com.example.app/.MainActivity         
Run Code Online (Sandbox Code Playgroud)

这导致:

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)
Run Code Online (Sandbox Code Playgroud)

UiAutomator所以本质上我的问题是,如何以我可以在运行时使用的方式运行应用程序?

提前致谢!

Hei*_*eli 3

对的,这是可能的:

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'
Run Code Online (Sandbox Code Playgroud)

2.AndroidManifest.xml中添加以下uses-library标签applicationinstrumentationmanifest

implementation 'androidx.test.ext:junit:1.1.2'
implementation 'androidx.test.uiautomator:uiautomator:2.2.0'
implementation 'androidx.test:runner:1.1.0'
Run Code Online (Sandbox Code Playgroud)

设置android:targetPackage为您自己的应用程序包名称。

    <!-- Add inside application tag -->
    <uses-library android:name="android.test.runner" />
Run Code Online (Sandbox Code Playgroud)

3.创建您的活动。你可以InstrumentationRegistry.getInstrumentation();在那里使用。

4.在应用程序类的同一源集中创建测试类(在src/main/java内)

    <!-- Add inside manifest tag -->
    <instrumentation
        android:name="androidx.test.runner.AndroidJUnitRunner"
        android:label="App"
        android:targetPackage="com.example.app" />
    </manifest>
Run Code Online (Sandbox Code Playgroud)

5.构建并安装应用程序。

6.使用以下命令运行应用程序: adb shell am instrument -w -m -e debug false -e class 'com.example.app.Test' com.example.app/androidx.test.runner.AndroidJUnitRunner

7.(可选)如果您想直接从runAndroid Studio 中的按钮执行它,则将其添加到android您的中build.gradle,它将更改必须创建测试类的位置,指向与主代码相同的文件夹:

sourceSets {
    androidTest {
        java.srcDir 'src/main/java'
    }
}
Run Code Online (Sandbox Code Playgroud)