錄製與回放
- 連接手機(打開文件傳輸)或者是打開模擬器
- cmd進入安裝sdk的AndroidSDK\Android_SDK_windows\tools目錄下
- 執行monkeyrunner recorder.py
recoder.py腳本內容
from com.android.monkeyrunner import MonkeyRunner as m
from com.android.monkeyrunner.recorder import MonkeyRecorder as Re
device=m.waitForConnection()
Re.start(device)
- 在monkeyrecorder中進行用例操作,然後導出(Export Actions),保存爲py文件
- 再執行monkeyrunner recorder_palyback.py 之前錄製腳本名
recorder_playback.py腳本內容
import sys
from com.android.monkeyrunner import MonkeyRunner
CMD_MAP = {
'TOUCH': lambda dev, arg: dev.touch(**arg),
'DRAG': lambda dev, arg: dev.drag(**arg),
'PRESS': lambda dev, arg: dev.press(**arg),
'TYPE': lambda dev, arg: dev.type(**arg),
'WAIT': lambda dev, arg: MonkeyRunner.sleep(**arg)
}
# Process a single file for the specified device.
def process_file(fp, device):
for line in fp:
(cmd, rest) = line.split('|')
try:
# Parse the pydict
rest = eval(rest)
except:
print 'unable to parse options'
continue
if cmd not in CMD_MAP:
print 'unknown command: ' + cmd
continue
CMD_MAP[cmd](device, rest)
def main():
file = sys.argv[1]
fp = open(file, 'r')
device = MonkeyRunner.waitForConnection()
process_file(fp, device)
fp.close();
if __name__ == '__main__':
main()
自己編寫腳本
#coding=utf-8
from com.android.monkeyrunner import MonkeyRunner,MonkeyDevice,MonkeyImage
device = MonkeyRunner.waitForConnection() #等待設備連接,可設置參數如:MonkeyRunner.waitForConnection(10,'emulator-5554')--等待時長與設備序列號
device.press('KEYCODE_HOME',MonkeyDevice.DOWN_AND_UP) #按HOME鍵
#device.reboot() #設備重啓
MonkeyRunner.sleep(3) #等待3秒
#device.wake() #設備喚醒
device.press('KEYCODE_MEMU',MonkeyDevice.DOWN_AND_UP) #按菜單鍵
device.removePackage('com.rfchina.app.supercommunity.Dev') #卸載包
print('success')
MonkeyRunner.sleep(1)
device.installPackage('C:\monkey\SuperCommunity_client_Test_release_v4.10.4_774.apk') #安裝包
print('success')
MonkeyRunner.sleep(2)
#啓動activity
componentName = "com.rfchina.app.supercommunity.client.StartActivity"
device.startActivity(component=componentName) #啓動活動
MonkeyRunner.sleep(2)
result = device.takeSnapshot() #快照
result.writeToFile(r'C:\monkey\result1.png','png') #保存快照
pic2 = MonkeyRunner.loadImageFromFile(r'C:\monkey\1.png')
if(result.sameAs(pic2,0.9)): #對比截屏和已保存的圖片
print("success")
else:
print("fail")
#點擊社區圈
device.touch(348,1125,"DOWN_AND_UP")
MonkeyRunner.sleep(2)
device.touch(666,85,"DOWN_AND_UP")
Content = 'monkeyrunner測試'
device.type(Content) #輸入內容
MonkeyRunner.sleep(2)
device.touch(666,96,"DOWN_AND_UP")
文件保存爲.mr文件,再用monkeyrunner 文件名,就可執行(執行期間可以看到模擬器或者真機在自動操作)