参照: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.

    1. Your first UIAutomation script

    2. Dealing with UIAElement and Accessibility
    3. Tips to simplify your life
    4. Advanced interactions
    5. The end
var target = UIATarget.localTarget();
var app = target.frontMostApp();
var window = app.mainWindow();
target.logElementTree();

Now, let’s put this in practice:

  1. Stop (⌘R) Instruments
  2. In the Scripts window, remove the current script
  3. Click on ’Add > Import’ and select TestAutomation/TestUI/Test-1.js
  4. 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:

  1. Launch Instruments (⌘I)
  2. Create a new script
  3. Select the Script editor
  4. In the bottom of the script editor, see that red button ?Press-it!
  5. 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的更多相关文章

  1. Django~automated tests

    def xx(): 冒号下一行要缩进 ATD http://blog.csdn.net/doupei2006/article/details/7657547 http://www.jb51.net/a ...

  2. iOS 强大第三方资源库

    Github用法 git-recipesGit recipes in Chinese. 高质量的Git中文教程. lark怎样在Github上面贡献代码 my-git有关 git 的学习资料 giti ...

  3. iOS 第三方库、插件、知名博客总结

    iOS 第三方库.插件.知名博客总结 用到的组件 1.通过CocoaPods安装 项目名称 项目信息 AFNetworking 网络请求组件 FMDB 本地数据库组件 SDWebImage 多个缩略图 ...

  4. iOS 资源大全

    这是个精心编排的列表,它包含了优秀的 iOS 框架.库.教程.XCode 插件.组件等等. 这个列表分为以下几个部分:框架( Frameworks ).组件( Components ).测试( Tes ...

  5. IOS中文版资源库

    Swift 语言写成的项目会被标记为  ★ ,AppleWatch 的项目则会被标记为 ▲. [转自]https://github.com/jobbole/awesome-ios-cn#librari ...

  6. [ZZ]Android UI Automated Testing

    Google Testing Blog最近发表了一篇Android UI Automated Testing,我把他转载过来,墙外地址:http://googletesting.blogspot.co ...

  7. How to: Run Tests from Microsoft Visual Studio

    https://msdn.microsoft.com/en-us/library/ms182470.aspx Running Automated Tests in Visual Studio Visu ...

  8. 墙裂推荐 iOS 资源大全

    这是个精心编排的列表,它包含了优秀的 iOS 框架.库.教程.XCode 插件.组件等等. 这个列表分为以下几个部分:框架( Frameworks ).组件( Components ).测试( Tes ...

  9. 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 ...

随机推荐

  1. 第3章 编写ROS程序-2

    1.发布者程序 在本节中,我们将看到如何发送随机生成的速度指令到一个turtlesim海龟,使它漫无目的地巡游.这个程序的源文件称为pubvel,这个程序展示了从代码中发布消息涉及的所有要素. 其代码 ...

  2. Updatepanel 中使用 Timer 控件 失去焦点问题

    在Update Panel 中 如果使用timer 定时刷新数据,会造成textbox 或者其他控件的焦点丢失问题. 所以 text box 不能和timer 放在同一个Updatepanel 中. ...

  3. HDU - 4284 Travel(floyd+状压dp)

    Travel PP loves travel. Her dream is to travel around country A which consists of N cities and M roa ...

  4. Halcon 和 C# 联合编程 - 如何使用开源项目 ViewROI

    声明 HWndCtrl _viewCtrl; ROIController _roiCtrl; 初始化 _viewCtrl = new HWndCtrl(hWindowControl); _roiCtr ...

  5. 权限验证MVC

    http://www.jb51.net/article/20147.htm  引用 <authentication mode="Forms"><!--权限受到阻碍 ...

  6. UGUI CanvasGroup

    说明,这种直接设置alpha的方法跟go的setActive(false)性能差不多,只少了激活和冻结冻结调用 http://blog.csdn.net/qq_28824335/article/det ...

  7. Codeforces Round #360 (Div. 1)A (二分图&dfs染色)

    题目链接:http://codeforces.com/problemset/problem/687/A 题意:给出一个n个点m条边的图,分别将每条边连接的两个点放到两个集合中,输出两个集合中的点,若不 ...

  8. codevs1051接龙游戏

    1051 接龙游戏  

  9. 剑指Offer的学习笔记(C#篇)-- 数字在排序数组中出现的次数

    题目描述 统计一个数字在排序数组中出现的次数. 一 . 题目分析 该题目并不是难题,但该题目考察目的是正确的选择合适的查找方法.题目中有一个关键词是:排序数组,也就是说,该数组已经排好了,我一开始直接 ...

  10. elasticsearc 参考资料

    _source 和store http://stackoverflow.com/questions/18833899/in-elasticsearch-what-happens-if-i-set-st ...