iOS Automated Tests with UIAutomation
参照:http://blog.manbolo.com/2012/04/08/ios-automated-tests-with-uiautomation#1
UI Automation JavaScript Reference
https://developer.apple.com/library/ios/documentation/DeveloperTools/Reference/UIAutomationRef/_index.html
Another framework to be mention is OCUnit, which is included in Xcode, and can be used to add unit tests to your app.
var target = UIATarget.localTarget();
var app = target.frontMostApp();
var window = app.mainWindow();
target.logElementTree();
Now, let’s put this in practice:
- Stop (⌘R) Instruments
- In the Scripts window, remove the current script
- Click on ’Add > Import’ and select TestAutomation/TestUI/Test-1.js
- Click on Record (⌘R) and watch what’s happens…
The script is:
var testName = "Test 1";
var target = UIATarget.localTarget();
var app = target.frontMostApp();
var window = app.mainWindow(); UIALogger.logStart( testName );
app.logElementTree(); //-- select the elements
UIALogger.logMessage( "Select the first tab" );
var tabBar = app.tabBar();
var selectedTabName = tabBar.selectedButton().name();
if (selectedTabName != "First") {
tabBar.buttons()["First"].tap();
} //-- tap on the text fiels
UIALogger.logMessage( "Tap on the text field now" );
var recipeName = "Unusually Long Name for a Recipe";
window.textFields()[0].setValue(recipeName); target.delay( 2 ); //-- tap on the text fiels
UIALogger.logMessage( "Dismiss the keyboard" );
app.logElementTree();
app.keyboard().buttons()["return"].tap(); var textValue = window.staticTexts()["RecipeName"].value();
if (textValue === recipeName){
UIALogger.logPass( testName );
}
else{
UIALogger.logFail( testName );
}
By the power of the command line
If you want to automate your scripts, you can launch them from the command line. In fact, I recommend to use this option, instead of using the Instruments graphical user interface. Instruments’s UI is slow, and tests keep running even when you’ve reached the end of them. Launching UIAutomation tests on command line is fast, and your scripts will stop at the end of the test.
Depending on you version of Xcode, the command line is slighty different.
In any version, to launch a script, you will need your UDID.
On Xcode >= 4.3 and < 4.5, type on a terminal:
instruments \
-w your_ios_udid \
-t "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Instruments/PlugIns/AutomationInstrument.bundle/Contents/Resources/Automation.tracetemplate" \
name_of_your_app \
-e UIASCRIPT absolute_path_to_the_test_file
On Xcode >= 4.5, type on a terminal:
instruments \
-w your_ios_udid \
-t "/Applications/Xcode.app/Contents/Applications/Instruments.app/Contents/PlugIns/AutomationInstrument.bundle/Contents/Resources/Automation.tracetemplate" \
name_of_your_app \
-e UIASCRIPT absolute_path_to_the_test_file
For instance, in my case (Xcode 4.3), the line looks like:
instruments -w a2de620d4fc33e91f1f2f8a8cb0841d2xxxxxxxx -t /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Instruments/PlugIns/AutomationInstrument.bundle/Contents/Resources/Automation.tracetemplate TestAutomation -e UIASCRIPT /Users/jc/Documents/Dev/TestAutomation/TestAutomation/TestUI/Test-2.js
If you are using a version of Xcode < 4.3, you will need to type:
instruments \
-w your_ios_device_udid \
-t "/Developer/Platforms/iPhoneOS.platform/Developer/Library/Instruments/PlugIns/AutomationInstrument.bundle/Contents/Resources/Automation.tracetemplate"
TestAutomation \
-e UIASCRIPT /Users/jc/Documents/Dev/TestAutomation/TestAutomation/TestUI/Test-2.js
Interactively record interaction
Instead of typing your script, you can record the interaction directly on the device or in the simulator, to replay them later. Do to this:
- Launch Instruments (⌘I)
- Create a new script
- Select the Script editor

- In the bottom of the script editor, see that red button ?
Press-it! - Now, you can play with your app; you will see the captured interactions appearing in the script window (even rotation event). Press the square button to stop recording.

“When things don’t work, add UIATarget.delay(1);”
While writing your script, you will play with timing, animations and so on. UIAutomation has various functions to get elements and wait for them even if they’re not displayed but the best advice is from this extra presentation:
4. Advanced interactions
Handling unexpected and expected alerts
Handling alert in automated tests has always been difficult: you’ve carefully written your scripts, launch your test suite just before going to bed, and, in the morning, you discover that all your tests has been ruined because your iPhone has received an unexpected text message that has blocked the tests. Well, UIAutomation helps you to deal with that.
By adding this code in your script,
UIATarget.onAlert = function onAlert(alert){
var title = alert.name();
UIALogger.logWarning("Alert with title ’" + title + "’ encountered!");
return false; // use default handler
}
and returning false, you ask UIAutomation to automatically dismiss any UIAlertView, so alerts won’t interfere with your tests. Your scripts will run as if there has never been any alert. But alerts can be part of your app and tested workflow so, in some case, you don’t wan’t to automatically dismiss it. To do so, you can test against the title of the alert, tap some buttons and return true. By returning true, you indicate UIAutomation that this alert must be considered as a part of your test and treated accordantly.
For instance, if you want to test the ’Add Something’ alert view by taping on an ’Add’ button, you could write:
UIATarget.onAlert = function onAlert(alert) {
var title = alert.name();
UIALogger.logWarning("Alert with title ’" + title + "’ encountered!");
if (title == "Add Something") {
alert.buttons()["Add"].tap();
return true; // bypass default handler
}
return false; // use default handler
}
Easy Baby!
Multitasking
Testing multitasking in your app is also very simple: let’s say you want to test that crazy background process you launch each time the app resumes from background and enter in - (void)applicationWillEnterForeground:(UIApplication *)applicationselector, you can send the app in background, wait for for 10 seconds, and resume it by calling:
UIATarget.localTarget().deactivateAppForDuration(10);
deactivateAppForDuration(duration) will pause the script, simulate the user taps the home button, (and send the app in background), wait, resume the app and resume the test script for you, in one line of code!.
Orientation
You can simulate the rotation of your iPhone. Again, pretty straightforward and easy:
var target = UIATarget.localTarget();
var app = target.frontMostApp();
// set landscape left
target.setDeviceOrientation(UIA_DEVICE_ORIENTATION_LANDSCAPELEFT);
UIALogger.logMessage("Current orientation is " + app.interfaceOrientation());
// portrait
target.setDeviceOrientation(UIA_DEVICE_ORIENTATION_PORTRAIT);
UIALogger.logMessage("Current orientation is " + app.interfaceOrientation());
Taking screenshot
You can easily take screenshot of the current state of your app. It can be useful to compare this to some reference image.
var target = UIATarget.localTarget();
target.captureScreenWithName( "screenshot1.png" );
The location of the screenshot will be inferred by the path you add in option -e UIARESULTSPATH results_path
Launching local script
Finally, you can launch any scripts (not only Javascript) that is on your local host. Combined with the capacity to take screenshots, you can imagine powerful automatic tests. You can use performTaskWithPathArgumentsTimeout(path, args, timeout)with pathcontaining the full path of your script, args an array of arguments to pass to your script, and timeout a … timeout!
var target = UIATarget.localTarget();
var host = target.host();
var result = host.performTaskWithPathArgumentsTimeout("/usr/bin/echo", ["Hello World"], 5);
When things don’t work, add UIATarget.delay(1);!
iOS Automated Tests with UIAutomation的更多相关文章
- Django~automated tests
def xx(): 冒号下一行要缩进 ATD http://blog.csdn.net/doupei2006/article/details/7657547 http://www.jb51.net/a ...
- iOS 强大第三方资源库
Github用法 git-recipesGit recipes in Chinese. 高质量的Git中文教程. lark怎样在Github上面贡献代码 my-git有关 git 的学习资料 giti ...
- iOS 第三方库、插件、知名博客总结
iOS 第三方库.插件.知名博客总结 用到的组件 1.通过CocoaPods安装 项目名称 项目信息 AFNetworking 网络请求组件 FMDB 本地数据库组件 SDWebImage 多个缩略图 ...
- iOS 资源大全
这是个精心编排的列表,它包含了优秀的 iOS 框架.库.教程.XCode 插件.组件等等. 这个列表分为以下几个部分:框架( Frameworks ).组件( Components ).测试( Tes ...
- IOS中文版资源库
Swift 语言写成的项目会被标记为 ★ ,AppleWatch 的项目则会被标记为 ▲. [转自]https://github.com/jobbole/awesome-ios-cn#librari ...
- [ZZ]Android UI Automated Testing
Google Testing Blog最近发表了一篇Android UI Automated Testing,我把他转载过来,墙外地址:http://googletesting.blogspot.co ...
- How to: Run Tests from Microsoft Visual Studio
https://msdn.microsoft.com/en-us/library/ms182470.aspx Running Automated Tests in Visual Studio Visu ...
- 墙裂推荐 iOS 资源大全
这是个精心编排的列表,它包含了优秀的 iOS 框架.库.教程.XCode 插件.组件等等. 这个列表分为以下几个部分:框架( Frameworks ).组件( Components ).测试( Tes ...
- C# Note37: Writing unit tests with use of mocking
前言 What's mocking and its benefits Mocking is an integral part of unit testing. Although you can run ...
随机推荐
- 5、scala面向对象-类
一.类 1.定义类 ##定义并调用 scala> :paste // Entering paste mode (ctrl-D to finish) class HelloWord { priva ...
- 常用的Elasticseaerch检索技巧汇总
本篇博客是对前期工作中遇到ES坑的一些小结,顺手记录下,方便日后查阅. 0.前言 为了讲解不同类型ES检索,我们将要对包含以下类型的文档集合进行检索: . title 标题: . authors 作者 ...
- hostent结构体和wsadata结构体
一.hostent结构体 使用这个东西,首先要包含2个头文件:#include <netdb.h>#include <sys/socket.h> struct hostent ...
- 数据库路由中间件MyCat - 使用篇(3)下篇
此文已由作者张镐薪授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 2. 配置conf/server.xml server.xml几乎保存了所有mycat需要的系统配置信息.其 ...
- Flask RESTful API搭建笔记
之前半年时间,来到项目的时候,已经有一些东西,大致就是IIS+MYSQL+PHP. 所以接着做,修修补补,Android/iOS与服务器数据库交换用PHP, Web那边则是JS+PHP,也没有前后端之 ...
- 搭建 Keras
首先安装ipython ipython安装完成以后出现如下界面 然后安装theano 中途安装因为网络不好,造成超时而停止安装或者停滞不前,则按下Ctrl+C,停止此操作,或者关掉Anaconda P ...
- Fedora下Msitools使用
msitools学习 msitools使用 wixl-heat使用 概述 打包程序就是把程序依赖的所有库文件和可执行文件以及其他一些资源文件按照源目录结构进行压缩,知道自己的程序依赖哪些库是简单的,但 ...
- Mujin Programming Challenge 2017A - Robot Racing【思维题】
题意: 给你n个人的位置,每个人能往后跳一格或两格到无人的位置,跳到0位置,这个人消失,n个人消失组成一个排列,问有多少种排列. 思路: 额,搞了一整场这个A...代码也巨挫了. 处理成1,3,5,7 ...
- JS 识别生日、性别、年龄
<script> function IdCard(UUserCard,num){ if(num==1){ //获取出生日期 birth=UUserCard.substring(6, 10) ...
- nginx 初了解
随着现代web开发的发展,restful,前后端分离,前端js框架的应用越来越普遍.很多web应用请求的接口可能根本就存在于不同的服务器,类似于微信,支付宝等等.这其中就会存在跨域的问题.简单来说,跨 ...