三步搞定android单元测试

发表于:2013-8-12 14:36

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:u011387452    来源:51Testing软件测试网采编

  1. 在File/AndroidManifest.xml中添加以下代码。

application标签中:
<uses-library android:name="android.test.runner" />

application标签外:
<uses-permission android:name="android.permission.RUN_INSTRUMENTATION" />
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.example.file" android:label="Test for my app"/>

  请注意,上面的"com.example.file"务必替换成你自己的程序包名。

  2. 新建一个测试类,确保继承AndroidTestCase类

public class FileServiceTest extends AndroidTestCase {
private static final String TAG="FileServiceTest";
public void testRead() throws Throwable{
FileService service = new FileService(this.getContext());
String result=service.read("jason.txt");
Log.i(TAG, result);
}
}

  3.在上面的测试类中右键run as-> Android JUnit Test。

  附上被测试的函数代码:

/**
* 读取文件内容
* @param fileName  文件名称
* @return 文件内容
* @throws Exception
*/
public String read(String fileName) throws Exception{
FileInputStream inStream=context.openFileInput(fileName);
ByteArrayOutputStream outStream= new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len=0;
while((len=inStream.read(buffer))!=-1){
outStream.write(buffer, 0, len);
}
byte[] data=outStream.toByteArray();
outStream.close();
inStream.close();
return new String(data);
}

《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号