Category: Mobile

App development for mobile devices such as iPhone and Android.

Getting started with UI Automation in Xcode 4

Did you know that with a little patience and some knowledge of JavaScript you can write automated UI tests against your iOS applications? What’s even better is with Xcode 4.2 installed its as easy as clicking a record button and having Instruments generate the test scripts for you.

For this tutorial I’m going to download the Core Data Recipes application from Apple’s developer website. Once you’ve opened the app in Xcode go ahead and click on
Product -> Profile in the menu bar (command + I works just as well) to launch the Instruments tool that we’ll be using to run our tests with.

You should see your application launched in the simulator along with a running instruments profiler. Form here you’re going to want to check that the Automation instrument has been created and then click on the Add button just below it to create a new Automator script.

After clicking on Add -> Create you will notice a record button looming towards the bottom that when clicked allows you to begin interacting with your application and generating the JavaScript necessary to automate the test.

Here’s a trivial example that I recorded using the sample application to demonstrate.

var target = UIATarget.localTarget();

target.frontMostApp().mainWindow().tableViews()["Empty list"].cells()["Chocolate cake with chocolate frosting, 1 hour, Chocolate Cake"].tap();
target.frontMostApp().navigationBar().rightButton().tap();
target.frontMostApp().mainWindow().tableViews()["Empty list"].cells()["Dessert"].tap();
target.frontMostApp().mainWindow().tableViews()["Empty list"].cells()["Snack"].tap();
target.frontMostApp().navigationBar().leftButton().tap();
target.frontMostApp().mainWindow().tableViews()["Empty list"].cells()["Snack"].tap();
target.frontMostApp().mainWindow().tableViews()["Empty list"].cells()["Dessert"].tap();
target.frontMostApp().navigationBar().leftButton().tap();
target.frontMostApp().navigationBar().rightButton().tap();
target.frontMostApp().navigationBar().leftButton().tap();

Having Xcode generate the script for you can test your patience with how it tries to target certain elements incorrectly but often times it will at the very least get you a good base to work from if you’re just getting the hang of how to ineract with your app.

It’s worth mentioning that this script will run just fine if you are dealing with UI elements that stay the same across test runs or otherwise remain static. If this isn’t the case then you may run into cases where elements have different attributes or no longer exist if you were to delete a row in a UITableView for example. This is where some knowledge of JavaScript (and the UI Automation Reference) comes in handy to check the existence and state of elements. This is beyond the scope of this article but one possible approach to this problem would be to restore your data prior to each test run.

You’ll notice that the third line has the cell contents hard coded into the script which is just another way of gaining access to it.

target.frontMostApp().mainWindow().tableViews()["Empty list"]
    .cells()["Chocolate cake with chocolate frosting, Chocolate Cake"].tap();

Thankfully we have a couple of much better options to achieve the same result. The first way is by using the element placement index inside of the cells array.

target.frontMostApp().mainWindow().tableViews()["Empty list"]
    .cells()[0].tap();

You can alternatively set the accessability label through Interface Builder.

The accessibilityLabel property can also be set at runtime if you so choose, this is most useful for dynamic layouts.

cell.isAccessibilityElement = YES;
cell.accessibilityLabel = @"Cake";

Given the nature of the Core Data Recipes sample application our best approach would be to use the cell index or full cell label text for demonstration purposes. Ideally the accessibility text would be part of your data source in some fashion so in code we could iterate over the data while creating the table view cells.

Taking another look at the script you can see a lot of repetitive ways of accessing elements, we can pull out some common pieces and have cached versions to work with instead. Not only does this make your script more readable but it will also help speed up the running times.

var target = UIATarget.localTarget();
var app = target.frontMostApp();
var window = app.mainWindow();
var navBar = window.navigationBar();

We’ll also go ahead and change the hardcoded string key to access the cell to an ordinal index value here as well by updating tableViews()["Empty list"] to be
tableViews()[0]

Now what’s left is a script that is much more maintainable going forward.

var target = UIATarget.localTarget();
var app = target.frontMostApp();
var window = app.mainWindow();
var navBar = window.navigationBar();

// Select Recipe
window.tableViews()[0].cells()[0].tap();

// Change Ingredient
navBar.rightButton().tap();
window.tableViews()[0].cells()["Dessert"].tap();
window.tableViews()[0].cells()["Snack"].tap();
navBar.leftButton().tap();

// Change Ingredient Again
window.tableViews()[0].cells()["Snack"].tap();
window.tableViews()[0].cells()["Dessert"].tap();
navBar.leftButton().tap();

// Done Editing
navBar.rightButton().tap();

// Back To Recipe List
navBar.leftButton().tap();

Where to go from here?

One aspect of the documentation that is worth exploring is the UIALogger class. UIALogger gives you the ability to define a beginning and end of your test cases and not only provide a means of structuring tests but you can record pass or fail messages to give more context to the results. These messages will get output in the Trace Log portion of the Instruments tool.

More

Blocks save the day

I’m consistently amazed how useful blocks are in Objective-C. So much so that I’ll be attempting to document useful ways that blocks can make your life easier as an iOS developer. Here’s the first of (hopefully) many posts of its kind.

Take this code

- (void)viewDidAppear:(BOOL)animated {
{
    UIView *viewToAnimate = ...
    [self performSelector:@selector(animateIt:) withObject:viewToAnimate afterDelay:1.0f];
}

-(void)animateIt:(id)sender 
{
    // animate viewToAnimate
}

It seems like this could be better by having the animation code where you have your selector delay setup. Well guess what? Blocks to the rescue!

@implementation NSObject (PerformBlockAfterDelay)

- (void)performBlock:(void (^)(void))block 
          afterDelay:(NSTimeInterval)delay 
{
    block = [[block copy] autorelease];
    [self performSelector:@selector(fireBlockAfterDelay:) 
               withObject:block 
               afterDelay:delay];
}

- (void)fireBlockAfterDelay:(void (^)(void))block 
{
    block();
}

@end

This snippet is using category that you can #import into your class. Using this in practice you get this.

- (void)viewDidAppear:(BOOL)animated {
{
    UIView *viewToAnimate = ...
    [self performBlock:^void() {
        // animate viewToAnimate
    } afterDelay:1.0f];
}

Credit goes out to this StackOverflow thread for the tip.

More

Cocoaconf 2011 Recap

Cocoaconf Logo

Cocoaconf actually took me by surprise as I just happened to hear about it from a tweet within a month of it taking place. It’s pretty rare to find developer events of this size so close by Detroit so I had to jump on the opportunity. Who would’ve thought that I would get so much out of spending a few days in Dublin, Ohio?

Cocoaconf is a brand new conference that’s geared towards a technical audience (eg: no vendors were present). There were sessions for many skill levels and even an all day “soup to nuts” workshop that created an iPhone app from scratch using many of the Cocoa API’s. The sessions that I found most helpful were ones that I don’t normally see too much coverage of like UIAutomation with tuneup_js as well as unit testing with ghunit and ocmock. I would say that the session that surprised me the most was on NSURLConnection and the different networking protocols and technologies that are present in Cocoa. Immediately I could see the benefit of things like Bonjour discovery and the AFNetworking library.

One session that I thought was unique was the “We Made An App For That” talks where attendees had the opportunity to talk about their experiences in building their app and give a demonstration of how their apps function. The apps ranged from one that had just been released within the last month and even one that had sold thirty thousand copies!

To help give the speakers feedback there were cocoa bucks being rewarded for those folks who filled out the questioners. These cocoa bucks were then entered in a drawing to win prizes at the end. This was clearly an important part of the conference as they were being handed out at all of the doors, and from the looks of things they had a good amount of them turned in. I actually didn’t realize at the time but quite a few of the books that were being given out were written by the speakers at Cocoaconf. This goes to show you the quality that was put into their debut event and from the sound of things it’s only going to be getting better.

More

WindyCityGo Mobile Conference

Earlier this month I had the opportunity to attend WindyCityGo in Chicago, IL with a few hundred fellow mobile developers. The two primary sponsors of the event were Groupon and ThoughtWorks who both have a strong presence within the city. A couple of my takeaways from the event were..

  • Boyd’s Law of Iteration: speed of iteration beats quality of iteration.
  • Mobile analytics tools like Flurry are a great way to learn about your audience.. however they are under scrutiny from apple because of how they can potentially track new iPhone models before they’ve been announced.
  • Consider doing low tech prototypes of your app first by taking pictures of interface sketches and then flipping through them to get a feel for how your app will behave.
  • In some cases you can simply give your images a css width attribute of 100% to make them more responsive to mobile screen dimensions.
  • The LLVM compiler and LLDB come with XCode4, however you can’t use LLDB on iOS projects yet.

Best of all, I was able to contribute on an open source project that allows for real time chat between an iPhone app and a Ruby on Rails website. Go check out the Groupon Chat project up on GitHub.

More