转载地址:http://blog.csdn.net/aijason/article/details/9984943
三步搞定android单元测试:
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"/>
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);
- }