在Android Studio中编写Uiautomator测试脚本在sdcard中写入文件
1. 插入代码
public void writeFile(String content){
try{
File file = new File("/sdcard/test.txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file);
fileWritter.write(content);
fileWritter.close();
}
catch (IOException e){
Log.d("TestFile", "File write error.");
e.printStackTrace();
}
}
2. 在AndroidMainfest.xml文件中添加权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
3. 运行
直接用Android Studio运行会报“java.io.IOException: Permission denied”的错误
查看自动运行执行的命令可以发现实际执行的命令是
01/23 15:49:42: Launching Tests in 'com.******
$ adb push ******\wear\build\outputs\apk\debug\wear-debug.apk /data/local/tmp/com.******
$ adb shell pm install -t -r "/data/local/tmp/com.******"
Success
APK installed in 7 s 116 ms
$ adb push ******\wear\build\outputs\apk\androidTest\debug\wear-debug-androidTest.apk /data/local/tmp/com.******.test
$ adb shell pm install -t -r "/data/local/tmp/com.******.test"
Success
APK installed in 3 s 390 ms
Running tests
$ adb shell am instrument -w -r -e package com.****** -e debug false com.******.test/android.support.test.runner.AndroidJUnitRunner
Client not ready yet..
Started running tests
这里安装了两个apk,一个工程的空apk,一个测试apk。如果单独安装测试apk无法运行,必须有一个依托的工程apk(可以为空)
如果要实现测试apk写入,不能使用自动的安装命令,需要添加-g参数,授予应用程序清单中列出的所有权限。
手动执行命令如下:
adb install -g -t -r .\app-debug.apk
adb install -g -t -r .\app-debug-androidTest.apk
adb shell am instrument -w -r -e debug false -e class 'com.***' com.***.test/android.support.test.runner.AndroidJUnitRunner