如何将参数传递给AndroidTestCase?

sel*_*rer 6 instrumentation android

我已经实现了Instrumentation和AndroidTestCase.

对于我的测试,我需要连接到外部WIFI设备.我希望测试人员能够为要使用的测试指定SSID.

给命令行(adb shell am instrument ...)运行测试不是问题,但是如何将SSID添加到命令行并在代码中提取它?

Tra*_*vis 13

为了扩展selalerer答案,可以使用Gradle指定的参数启动检测测试:

./gradlew -Pandroid.testInstrumentationRunnerArguments.exampleArgument=hello connectedAndroidTest
Run Code Online (Sandbox Code Playgroud)

您可以使用以下方法检索检测参数:

InstrumentationRegistry.getArguments().getString("exampleArgument") // returns "hello"
Run Code Online (Sandbox Code Playgroud)

  • 这个答案比公认的答案更简单明了。 (3认同)

sel*_*rer 10

找到了解决方案.

我让我的测试运行器继承自InstrumentationTestRunner并在onCreate()中获取额外数据:

public class MyTestRunner extends InstrumentationTestRunner {

    public static String BAR;

    public void onCreate(Bundle arguments) {

        if (null != arguments) {    
            BAR = (String) arguments.get("foo"));
        }    
        super.onCreate(arguments);
    }
}
Run Code Online (Sandbox Code Playgroud)

我添加到Android.mk:

LOCAL_JAVA_LIBRARIES := android.test.runner
Run Code Online (Sandbox Code Playgroud)

并且到AndroidManifest.xml:

<instrumentation 
    android:name="com.example.MyTestRunner"
    android:targetPackage="com.example" />
Run Code Online (Sandbox Code Playgroud)

使用此命令行运行它:

adb shell am instrument -w -e foo the_value_of_bar com.example/com.example.MyTestRunner
Run Code Online (Sandbox Code Playgroud)

我能够从命令行获取'foo'参数并在我的AndroidTestCase中使用BAR.