android单元测试环境搭建及运行

业务层类代码:

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 block
			e.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 block
			e.printStackTrace();
		}
		
	}

}

右击测试类——run as——android junit test;

如果运行无错,则可以在虚拟器中运行



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值