Android Basics Dry (ii): Android Test and analysis

Source: Internet
Author: User
Tags xml parser

1. Related Concepts of testing

1, according to whether you know the source code classification:

黑盒测试: a - b - c  边值测试白盒测试: 根据源代码写测试方法 或者 测试用例;

2, according to the size of the test classification:

方法测试:写完一个方法后就测试单元测试:测试一个能够独立运行的业务逻辑单元;集成测试:整体测试项目 联调系统测试:对整个系统进行测试

3, according to the level of violence tested:

1、冒烟测试:高频次的点击软件2、压力测试:使用测试工具:LoadRunner、Jmeter
2. Unit Testing

Junit

01_Junit单元测试 does not specify a android.test.InstrumentationTestRunner instrumentation or does not declare uses-library android.test.runner in its AndroidManifest.xml

Steps for unit Testing:

1, write a business class, write a business method:

public class CalcService {public static int add(int x,int y){        return x+y;}

}

2, write a test class, write a test method, used to test the business method

public class CalcServiceTest extends AndroidTestCase{public void testAdd(){    int result = CalcService.add(4, 5);    assertEquals(9, result);    }}

3. Add the package required for the test in the manifest file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.itheima.junit"android:versionCode="1"android:versionName="1.0" ><!-- 添加指令集,添加到manifest节点的里面,指令集会把应用程序部署到模拟器上运行 --><instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.itheima.junit"></instrumentation><application    android:allowBackup="true"    android:icon="@drawable/ic_launcher"    android:label="@string/app_name"    android:theme="@style/AppTheme" >    <!-- 添加JUnit的测试包 ,添加到application节点的里面-->    <uses-library android:name="android.test.runner"/>        ....</application></manifest>
Use of 3.Logcat logging tools

Level of log:
Error: Highest level, error message, red
Warn: Relatively high, warning message, orange
Debug: High, Debug info, Blue
Info: General, general information, Green
VERBOSE: general, all information, black

4. Storing data to a file

How the Android app stores data:

1、保存到文件2、SQLite数据库3、内容提供者4、sharedproferrences保存数据5、网络/data/data/应用包名/info.txt
5. Read the data from the file and display it to the interface

(1) To save the file to the directory of the current application step:

1、创建一个文件,目录/data/data/<包名>/文件名2、创建一个文件输出流,把数据写到文件上3、关闭输出流。代码:            //保存数据            File file = new File("/data/data/com.itheima.login/info.txt");            FileOutputStream fos = new FileOutputStream(file);            String info = qq + "##"+ pwd;            fos.write(info.getBytes());                        fos.close();            Toast.makeText(this, "保存数据成功", 0).show();

(2) Read the data in the file and display it to the interface

@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);            Setcontentview (R.layout.activity_main);        ET_QQ = (EditText) Findviewbyid (R.ID.ET_QQ);        Et_pwd = (EditText) Findviewbyid (R.ID.ET_PWD);        CB = (CheckBox) Findviewbyid (R.ID.CB);    Read the data in the file and display it to the interface map<string,string> Map = Readinfo (this);                if (map! = null) {Et_qq.settext (Map.get ("QQ"));    Et_pwd.settext (Map.get ("pwd"));    }}/** * Read the data in the file * @param ctx * @return */public map<string,string> readinfo (Context ctx) {String QQ = ";    String pwd = "";    map<string,string> map = new hashmap<string,string> ();        try {File File = new file ("/data/data/com.itheima.login/files/info.txt");        FileReader FR = new FileReader (file);        BufferedReader br = new BufferedReader (FR);                String info = br.readline ();        string[] Array = Info.split ("# #");        QQ = array[0]; PWD = ArraY[1];        Map.put ("QQ", QQ);        Map.put ("pwd", PWD);            return map;        } catch (Exception e) {e.printstacktrace ();    return null;     }        }
6. Store to SD card (emphasis)
异常信息:09-21 23:25:32.068: W/System.err(24718): java.io.FileNotFoundException: /storage/sdcard/info.txt: open failed: EACCES (Permission denied)

Steps:

1、  在SD卡上创建一个文件,2、创建一个输出流往sd卡上写数据String data = "dsfdsae";                File file = new File(Environment.getExternalStorageDirectory(), "info.txt");                FileOutputStream fos = new FileOutputStream(file);        fos.write(data.getBytes());                 fos.close();3、在清单文件中添加访问SD卡的权限 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
7. Get the SD size and available space
//获得sd卡的目录对象    File file = Environment.getExternalStorageDirectory();        //获得sd卡总空间的大小    long total =  file.getTotalSpace();        //转换数据大小的数据单位    String totalSize = Formatter.formatFileSize(this, total);    //获得sd卡剩余空间的大小    long usable = file.getUsableSpace();        String usableSize = Formatter.formatFileSize(this, usable);        tv.setText(usableSize+"/"+totalSize);
8. The concept of file permissions
文件的4种操作模式:Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可以使用Context.MODE_APPENDContext.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件。MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。如果希望文件被其他应用读和写,可以传入:   openFileOutput("itcast.txt", Context.MODE_WORLD_READABLE +             Context.MODE_WORLD_WRITEABLE);android有一套自己的安全模型,当应用程序(.apk)在安装时系统就会分配给他一个userid,当该应用要去访问其他资源比如文件的时候,就需要userid匹配。默认情况下,任何应用创建的文件,sharedpreferences,数据库都应该是私有的(位于/data/data/<package name>/files),其他程序无法访问。除非在创建时指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE ,只有这样其他程序才能正确访问。
9.SharedPreferences Second Storage method (emphasis)
The 
  is used primarily for (1) saving data to sharedpreferences public void Save (View v) {String data = Et.gettext (). toString (). Trim (    );        if (Textutils.isempty (data)) {Toast.maketext (this, "Please enter data", 0). Show ();    Return }else{//Get a sharedpreferences sharedpreferences sp = this.getsharedpreferences ("info", Context.mode        _private);                Sharedpreferences provides an editor to help us save the data Editor editor = Sp.edit ();                Editor.putstring ("Data", data);    Save the data in Sharedpreferences editor.commit ();    }} (2) Read data from Sharedpreferences public String ReadData () {string data; try {//Get a sharedpreferences sharedpreferences sp = this.getsharedpreferences ("info", context.mode_private)         ;    Data is obtained according to the parameter name sp.getstring ("data", NULL);        } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();    data = "";    } return data; } 
10. Using the serializer to generate an XML file
1, initialize an Xml file serializer XmlSerializer serializer = Xml.newserializer ();        2. Initialize the sequencer parameter file File = new file (Environment.getexternalstoragedirectory (), "Backup.xml");        FileOutputStream fos = new FileOutputStream (file);        Serializer.setoutput (FOS, "UTF-8");        3. Start writing the XML file.        Serializer.startdocument ("UTF-8", true);        Serializer.starttag (NULL, "SMSS");            for (Smsinfo Info:smsinfos) {//Start writing SMS node Serializer.starttag (NULL, "SMS");            Start writing body node Serializer.starttag (null, "body");            Serializer.text (Info.getbody ());                         Body node end Serializer.endtag (null, "body");            Start writing address node Serializer.starttag (NULL, "address");            Serializer.text (Info.getaddress ());                        Serializer.endtag (NULL, "address");            Start writing data node Serializer.starttag (NULL, "date");            Serializer.text (Info.getdate () + ""); SeriaLizer.endtag (NULL, "date");        SMS node end serializer.endtag (null, "SMS");        }//SMSS root node end serializer.endtag (null, "SMSS");        XML end Serializer.enddocument ();                Fos.close ();    Toast.maketext (This, "Backup SMS Success", 0). Show ();        } catch (Exception e) {e.printstacktrace ();    Toast.maketext (This, "Backup SMS Failed", 0). Show (); }
11. Using pull to parse data in XML format (important)
public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);   // 设置activity显示的布局    setContentView(R.layout.activity_main);    TextView tv_info = (TextView) findViewById(R.id.tv_info);    StringBuilder sb = new StringBuilder();    try {        //获取我们解析出来的天气信息        List<Channel> channels = WeatherService.getAllWeatherInfos(getClass().getClassLoader().getResourceAsStream("weather.xml"));        for(Channel channel : channels){            sb.append(channel.toString());            sb.append("\n");        }        //把解析出来的天气信息设置到textview上        tv_info.setText(sb.toString());        } catch (Exception e) {        e.printStackTrace();        Toast.makeText(this, "解析天气信息失败", 0).show();    }    }}
  public class WeatherService {/** * The data returned by the parsing server gets the weather information * @param the stream containing the weather information returned by the IS server (XML) * @return */public static list<    Channel> Getallweatherinfos (InputStream is) throws exception{list<channel> channels = null;    Channel channel = NULL;    1. Get the XML parser xmlpullparser parser = Xml.newpullparser ();    2. Set the XML parser parameter Parser.setinput (IS, "utf-8");        3. Start parsing the XML file. int type = Parser.geteventtype ();//Gets the type of the current event while (type!=xmlpullparser.end_document) {//requires the pull parser to parse to the end of the file s                Witch (type) {case XmlPullParser.START_TAG:if ("Weather". Equals (Parser.getname ())) {//Total start node Channels = new arraylist<channel> ();                Initializes the collection}else if ("Channel". Equals (Parser.getname ())) {//The information for a city begins.                Channel = new channel ();                Gets the property value of the id String id = parser.getattributevalue (0);                Channel.setid (Integer.parseint (id)); Parse City node}else if ("City". Equals (PARser.getname ())) {String city = Parser.nexttext ();                Channel.setcity (city);                Parse temperature node}else if ("Temp". Equals (Parser.getname ())) {String temp = Parser.nexttext ();                Channel.settemp (temp);                Parse the Wind node}else if ("Windy". Equals (Parser.getname ())) {String winds = parser.nexttext ();                 Channel.setwind (wind);                Resolves the pm250 node}else if ("pm250". Equals (Parser.getname ())) {String pm250 = Parser.nexttext ();            CHANNEL.SETPM250 (Integer.parseint (pm250));        } break; Judge the end node of the XML case XmlPullParser.END_TAG:if ("channel". Equals (Parser.getname ())) {//To parse the content                Added to the set Channels.add (channel);            channel = null;        } break;    } type = Parser.next ();    } is.close (); Return channels;//The collection of all the Channels back}}

Android Basics Dry (ii): Android Test and parsing

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.