android單元測試環境搭建及運行

來源:互聯網
上載者:User

業務層類代碼:

package cn.bzu.fileoperation;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import android.content.Context;public class FileService {private Context context;public FileService(Context context) {super();this.context = context;}//儲存資料public  void save(String fileName,String content) throws Exception{FileOutputStream fos=context.openFileOutput(fileName, Context.MODE_PRIVATE);fos.write(content.getBytes());fos.close();}//讀取資料public String readFile(String filename) throws IOException{FileInputStream fis=context.openFileInput(filename);int len=0;byte[] buffer=new byte[1024];ByteArrayOutputStream baos=new ByteArrayOutputStream();//往記憶體中輸出資料while((len=fis.read(buffer))!=-1){//如果資料量很大,第2次讀取的資料有可能會把第1次讀取的資料給覆蓋掉baos.write(buffer, 0, len);}byte[] data=baos.toByteArray();//得到記憶體中的資料 以二進位存放的baos.close();fis.close();return new String(data);//根據位元據轉換成所對應的字串}}

單元測試環境搭建:

在AndroidManifest.xml中<application></application>下添加代碼:

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

在<application></application>外添加代碼:

 <instrumentation        android:name="android.test.InstrumentationTestRunner"        android:targetPackage="cn.bzu.fileoperation" >    </instrumentation>

業務層測試類別代碼:

package cn.bzu.fileoperation;import java.io.IOException;import android.test.AndroidTestCase;public class FileServiceTest extends AndroidTestCase {public void testSaveFile(){FileService fileService=new FileService(getContext());try {fileService.save("file2.txt", "啦啦啦啦啦拉了拉啦啦啦");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void testReadFile(){FileService fileService=new FileService(getContext());try {String s=fileService.readFile("file2.txt");System.out.print(s);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

右擊測試類別——run as——android junit test;

如果運行無錯,則可以在虛擬器中運行

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.