How to pass an argument to an AndroidTestCase?

本小妞迷上赌 提交于 2019-11-30 15:26:27

问题


I've implemented an Instrumentation and an AndroidTestCase.

For my tests I need to connect to an external WIFI device. I want the testers to be able to specify an SSID for the test to use.

Giving the the command line (adb shell am instrument ...) to run the test is not a problem, but how can I add the SSID to the command line and extract it in the code?


回答1:


To expand on selalerer's answer, instrumentation test(s) can be started with arguments specified via Gradle:

./gradlew -Pandroid.testInstrumentationRunnerArguments.exampleArgument=hello connectedAndroidTest

You can retrieve instrumentation arguments using:

InstrumentationRegistry.getArguments().getString("exampleArgument") // returns "hello"



回答2:


Found a solution.

I made my test-runner inherit from InstrumentationTestRunner and took the extra data in 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);
    }
}

I added to Android.mk:

LOCAL_JAVA_LIBRARIES := android.test.runner

And to AndroidManifest.xml:

<instrumentation 
    android:name="com.example.MyTestRunner"
    android:targetPackage="com.example" />

Ran it using this command line:

adb shell am instrument -w -e foo the_value_of_bar com.example/com.example.MyTestRunner

I was able to get the 'foo' parameter from the command line and use BAR in my AndroidTestCase.




回答3:


This sounds like the Parameterised JUnit Test use-case.

Check out the brief tutorial here - note that you will need to be using JUnit4 and I'm not sure Android's testing framework is ready for that.

That said, JUnit4 is backward compatible to JUnit3 so in-theory it'll be possible to use JUnit4 annotations under the android test case runner with a bit of build path tomfoolery.



来源:https://stackoverflow.com/questions/15188756/how-to-pass-an-argument-to-an-androidtestcase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!