android单元测试

    技术2022-05-19  27

    Android 的开发应该遵循以下原则

    1>业务层代码( Android Junit

    2>先设计界面

    3>设计 Activity

    Android开发应该遵循 mvc 设计模式开发,所以我们先开发业务层代码,业务层是最复杂的一层,所以我们先要测试业务层,下面就以一个存储和读取文件的例子来说明测试的步骤

    FileService .java

    public   class  FileService {

    /**

     * 写入文件

     *  @param  out

     *  @param  string

     *  @throws  Exception

     */

    public   static   void  write(OutputStream out, String string)  throws  Exception {

    out.write(string.getBytes());

    out.close();

    }

    /**

     * 读取文件

     *  @param  input

     *  @return

     *  @throws  Exception

     */

    public   static  String read(InputStream input)  throws  Exception {

    StringBuffer sb =  new  StringBuffer();

    int  len = -1;

    byte [] buffer =  new   byte [1024];

    while ((len = input.read(buffer)) != -1) {

    sb.append( new  String(buffer, 0, len));

    }

    return  sb.toString();

    }

    }

    测试方法,测试方法继承 AndroidTestCase 类,此类应该和 activity在同一包中

     

    public   class  FileServiceTest  extends   AndroidTestCase  {

    public   void  testWrite()  throws  Exception {

    OutputStream outStream =  this . mContext .openFileOutput( "wangpeng.txt" , Context. MODE_PRIVATE );

    FileService. write (outStream,  "wp love xmm" );

    }

    public   void  testRead()  throws  Exception {

    InputStream input =  this . mContext .openFileInput( "wangpeng.txt" );

    String string = FileService. read (input);

    System. out .println( "---------->"  + string);

    }

    }

    AndroidTestCase   类中提供了一个 content的上下文的对象,这样就可以得到输入流和输出流

    需要注意的是,需要在配置文件中加上

    < application   android:icon = "@drawable/icon"   android:label = "@string/app_name" >

         < uses-library   android:name = "android.test.runner"   />

             < activity   android:name = ".FileActivity"

                       android:label = "@string/app_name" >

                 < intent-filter >

                     < action   android:name = "android.intent.action.MAIN"   />

                     < category   android:name = "android.intent.category.LAUNCHER"   />

                 </ intent-filter >

             </ activity >

     

         </ application >

          < instrumentation   android:name = "android.test.InstrumentationTestRunner"

       android:targetPackage = "com.wp.file.activity"   android:label = "Tests for My App"   />

     

    这样就可以进行测试了

     


    最新回复(0)