Robotium script encapsulated as APK, to achieve out-of-phone data cable, use the button to control the operation of the use of small functions

Source: Internet
Author: User

Recently has been completed some robotium small function, for more convenient to complete a number of small functions of the test, or can be said to be used for entertainment, kidnap group inside the Great God ideas, this extension, and finally to realize this function

---------------encapsulate the Robotium script as an apk and use the button to control how much coverage the use case runs, and the test results are entered into the phone's SD card directory with a simple XML file----------------------

Don't say much nonsense, positive questions:

First, make it clear that this article is implemented without exception to the Robotium script you write

Second, clarify the idea:

1. We need a well-functioning, logical Robotium project

2. We need a way to save the results of a script use case to a local

3. We need an activity, a button, and a button click event to run our Robotium script

Third, first introduce the function of the script use case running results, we all know that the Robotium use case is dependent on junit instrumentation, so, about the output of the result, we need to rewrite the Instrumentationtestrunner class

1PackageBaih;23ImportJava.io.File;4ImportJava.io.FileWriter;5ImportJava.io.IOException;6ImportJava.io.Writer;78ImportOrg.xmlpull.v1.XmlPullParserFactory;9ImportOrg.xmlpull.v1.XmlSerializer;1011ImportAndroid.content.Context;12ImportAndroid.os.Bundle;13ImportAndroid.os.Environment;1415/**16* This Test runner creates a test-all.xml in the files directory of the the application under test. The output is compatible with the Junitreport ant task, the format17* That's understood by Hudson. Currently this implementation does isn't implement the all aspects of the junitreport format, but enough for Hudson to parse The test results.18*/19PublicClass InstrumentationtestrunnerExtendsAndroid.test.InstrumentationTestRunner {20PrivateWriter Mwriter;21stPrivateXmlSerializer Mtestsuiteserializer;22PrivateLongmteststarted;23PrivateStaticFinal String junit_xml_file = "Test-all.xml";242526@Override27PublicvoidOnStart () {28Try{File Filerobo =NewFile (Gettestresultdir (Gettargetcontext ()));30if (!Filerobo.exists ()) {31Filerobo.mkdir ();32}33If(Issdcardavaliable ()) {File Resultfile =NewFile (Gettestresultdir (Gettargetcontext ()), junit_xml_file);Startjunitoutput (NewFileWriter (Resultfile));36}Else{Panax Notoginseng Startjunitoutput (New FileWriter (NewFile (Gettargetcontext (). Getfilesdir (), junit_xml_file)));38}39}40Catch(IOException e) {41ThrowNewRuntimeException (e);42}43Super. OnStart ();44}4546voidStartjunitoutput (writer writer) {47Try{Mwriter =WriterMtestsuiteserializer =Newserializer (Mwriter);Mtestsuiteserializer.startdocument (NullNull);Wuyi Mtestsuiteserializer.starttag (NULL, "Testsuites");Mtestsuiteserializer.starttag (NULL, "Testsuite");53}Catch(Exception e) {54ThrowNewRuntimeException (e);55}56}5758/**59* Determine if the SD card exists60*@return61*/62PrivateBooleanIssdcardavaliable () {63ReturnEnvironment.getexternalstoragestate ()64. Equals (environment.media_mounted);65}6667/**68* Get the path where the test results report file is located69*@paramContext of the project under test70*@returnReturns the path where the test results report file is located71*/72PrivateString Gettestresultdir (Context context) {PackageName String = "/" + "Robotium";FilePath String = Context.getcachedir (). GetPath () +PackageName;7576if (Android.os.Build.VERSION.SDK_INT < 8){ if (issdcardavaliable ()) {filepath = Environment.getexternalstoragedirectory (). GetAbsolutePath () + PackageName; }else{(Issdcardavaliable ()) {filepath = Environment.getexternalstoragedirectory (). GetAbsolutePath () + PackageName; (filepath); * XmlSerializer Newserializer (writer writer) {Xmlpullparserfactory pf = xmlpullparserfactory . newinstance (); XmlSerializer serializer = Pf.newserializer (); Serializer.setoutput (writer); Serializer return; 94} catch (Exception e) {sendstatus throw new RuntimeException (e);] (+)-98 @Override100 public void Resul (int. Tcode, Bundle results) {101 Super.sendstatus (ResultCode, results); 102 switch (ResultCode) {103 Case Report_value_result_ error:104 case report_value_result_failure:105 Case report_value_result_ok:106 try {107 Recordtestresult (ResultCode, results); 108} catch (IOException e) {109 throw new RuntimeException (e);}111 break;112 Case Report_value_result_start:113 Recordteststart (results); default:115 break;116}117}118 119 void Recordteststart (Bundle results) {Mteststa rted = System.currenttimemillis (); 121}122 123 void Recordtestresult (int resultcode, Bundle results) throws IOException {1 Float time = (System.currenttimemillis ()-mteststarted)/1000.0f;125 String className = results.getstring (report_key_ Name_class); 126 string testMethod = Results.getstring (report_key_name_test); 127 string stack = results.getstring ( report_key_stack); int current = Results.getint (report_key_num_current), 129 int total = Results.getint (report_key_ Num_total), 131 mtestsuiteserializer.starttag (null, "TestCase"), Mtestsuiteserializer.attribute (null, " ClassName ", classname); 133 mtestsuiteserializer.attribute (NULL," name ", TestMethod); 134 135 if (ResultCode! = Report_ VALUE_RESULT_OK) {136 Mtestsuiteserializer.starttag (NULL, "failure"); 137 if (stack! = null) {138 String reason = Stack.sub String (0, Stack.indexof (' \ n ')); 139 String message = ""; 140 int index = reason.indexof (': '); 141 if (Index >-1) {142 message = reason.substring (index+1); 143 reason = Reason.subs Tring (0, index); 144}145 Mtestsuiteserializer.attribute (NULL, "message", message); 146 Mtestsuiteserializer.attribute (NULL, "type", reason); 147 mtestsuiteserializer.text (stack); 148}149 Mtestsuiteserializer.endtag (NULL, "failure"); 151} else {Mtestsuiteserializer.attribute (null, "Time", String.Format ("%.3f", Time)); 152}153 Mtestsuiteserializer.endtag (NULL, "testcase"); 154 if (current = = total) {155 Mtestsuiteserializer.starttag (null, "System-out"); 156 Mtestsuiteserializer.endtag (NULL, "System-out"); 157 mtestsuiteserializer.starttag (NULL, "System-err"); 158 mtestsuiteserializer.endtag (NULL, " System-err "); 159 Mtestsuiteserializer.endtag (NULL," Testsuite "); Mtestsuiteserializer.flush (); 161}162}163 164 @ Override165 public void Finish (int resultcode, Bundle results) {166 endtestsuites (); 167 super.finish (ResultCode, results ); 168}169 Endtestsuites () {171 try {172 Mtestsuiteserializer.endtag (null, "testsuites"); 173 mtestsuiteserializer.enddocument (); 174 Mtestsuiteserializer.flush (); 175 Mwriter.flush (); 176 mwriter.close (); 177} catch (IOException e) {178 throw new RuntimeException (e); 179}180}181}

After rewriting the Instrumentationtestrunner class, you need to set the run configurations under our test project, right--move to run As-run configurations-android JUnit on your test project Test, change your project run instrumentation Runner, if not changed, default is Android.test.InstrumentationTestRunner

The position of the red box body circled needs to be changed to the Instrumentationtestrunner path you rewritten

After completing the above steps, you can then run the Robotium script, which will generate a file named Test-all.xml in the folder named Robotium under your phone's root directory to record the results of your script running as follows:

Run normal results, will show the run time, run the error of the use case, will print error message, as for the error message in the Chinese hint, is my use case to add the assertion, you can discretion

Complete this step and you can implement our package APK program. Package apk, first, we need an activity

The interface is relatively down, will look. For the creation and declaration of activity, please do your own Baidu

One or more buttons can be placed in the activity, since Robotium can be run using the command line, so we can use the OnClick event of different buttons to execute different scripts

As above: Attach various command-line startup commands:

Run All test Cases:

ADB shell am instrument-w packagename/instrumentationtestrunnername

Run a single test class or a testsuite
ADB shell am INSTRUMENT-E class packagename.testclassname-w Packagename/instrumentationtestrunnername

Run a test method inside a test class
ADB shell am INSTRUMENT-E class package name. Test Class Name # Method name-W project name. Package name/instrumentationtestrunner class name

Note: Before you write your code, test the command you are using in CMD to run correctly

After completing the above steps, we can package the entire test project as an APK file, remember the signature needs to sign the debug signature, then ... Install it on your phone, unplug the damn data cable, click the button, and start abusing your phone:)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.