Working with iOS Automation using XCUITest

XCUITest

The significant share held by iOS in the mobile market, comprising approximately 25–30% of the global smartphone market, underscores the necessity for robust testing methodologies to guarantee a seamless user experience, given the notable presence and popularity of iOS devices such as iPhones and iPads.

Why should one use the iOS native language for automation?

Let’s explore the rationale behind using iOS’s native language for automation. We outline the synergy between iOS’s native tools and the apps they test, emphasizing the smooth integration and the efficiency gains. Understanding this compatibility is crucial for professionals looking to streamline their automation processes in the iOS ecosystem.

  1. Access to Native APIs: Directly interact with iOS APIs for comprehensive device interaction.
  2. Optimized User Experience: Accurately replicate real user interactions for a seamless user experience.
  3. Performance and Efficiency: Achieve high-performance automation through iOS native languages.
  4. Seamless Integration: Ensure seamless integration by using the same language and platform as the iOS app.
  5. Security and Privacy: Enhance security by reducing risks associated with external tools or frameworks.
  6. Continuous Integration and Continuous Deployment (CI/CD): Seamless integration into CI/CD pipelines with native automation.
  7. Long-Term Viability: Ensure compatibility with iOS updates and changes for long-term viability.

Excuses for not using XCUITest:

Often, developers have reservations about adopting new tools like XCUITest. Our aim should be to confront these doubts head-on, dispelling myths and providing clear, factual insights into the capabilities of XCUITest.

Here are some excuses you will often come across: 

  1. We want a cross-platform solution for both iOS & Android.
  2. Where can we find engineering with Swift skills?
  3. We made a decision in the past to use another third-party tool and invested heavily in it.
  4. XCTest is still considered new.
  5. It still cannot automate hybrid iOS apps.

Pros of using XCUITest:

XCUITest comes with a host of benefits that make it an appealing choice for iOS automation. Here, we delve into its main advantages, from its inherent efficiency and Apple’s backing to its role in enhancing app accessibility. 

Here is how XCUITest stands out as a robust testing solution.

  1. Native & Faster than many other popular functional test frameworks.
  2. Managed by Apple.
  3. Enhance the accessibility of iOS apps.
  4. No need to install anything separately.
  5. XCUITest gives a chance to collaborate with developers and find internal issues in the app.
  6. Xcode Test recorder.

Comparison with Appium:

Choosing the right tool for automation can be challenging. This section offers a thorough comparison between XCUITest and Appium, highlighting the differences and strengths of each. Let’s look at their features that will help you make an informed decision on which tool better suits your project’s needs.

CriteriaAppiumEspressoXCUITest
AboutAppium is an open source tool.Espresso Testing Framework is an open-source framework created by Google for AndroidApple’s own product so less likely to have compatibility issues emerge when new versions of Xcode are launched
Environmental SetupRequires tedious setup(Webdriver Agent setup, Appium & library files)Easy, java JDK, latest Android Studio, Android SDK, Gradle build tool required onlyXCode & simulators
App Source CodeNo, requires signed IPA/APK filesYesYes
Language SupportJava, Obj-C, JS, PHP, Python, Ruby, C#, Perl, ClojureJavaObjective-C / Swift
Record & PlaybackRecords using Xpath object identifiers onlyUsing Espresso Test RecorderRecords using XCUIElement with Accessibility identifiers & XCUIElementQuery
Script DesignInbuilt support is provided along with 3rd party librariesEasy using JavaEasy using Swift, Privilege in adding accessibility ID for elements
Continuous IntegrationSupports CI Tools like Jenkins, Travis, etcSupports CI tools like Jenkins, etcSupport OS X Server & other CI tools like Jenkins
Test ReportCustomizable Reports are requiredInbuilt HTML reportingAppium is an open-source tool.
Execution SpeedVery slowFasterFaster
Object InspectionHuge pages will take longer time to inspectFast using ViewMatchersFaster with debug view hierarchy

What is XCTest & XCUITest:

  • XCTest is a framework integrated into Xcode, enabling test writing for iOS apps without additional dependencies.
  • XCUITest, launched by Apple in 2015, is a UI testing framework.
  • Using Swift/Objective-C, XCUITest allows the creation of automated tests for iOS apps.

XCUITest Prerequisites & Setup:

Starting with XCUITest involves understanding its prerequisites and setup process. This section serves as a foundational guide, detailing the steps and requirements to get up and running with XCUITest. It’s a practical walkthrough for developers new to this tool, ensuring a smooth transition into the world of iOS automation.

  • Xcode: Essential for XCUITest due to its tight integration with Xcode.
  • Swift or Objective-C knowledge: Crucial for script writing and comprehension in XCUITest.

Test Pyramid approach for XCTest:

The test pyramid model emphasizes a foundation of unit tests (XCTest), followed by integration tests, and places UI tests, including XCUITest, at the top layer. XCUITest complements the UI testing layer within the test pyramid, ensuring a balanced testing strategy across different levels.

Most used Package Managers in Xcode:

Package managers play a crucial role in iOS development. This section reviews the most commonly used package managers in Xcode, discussing how they streamline managing dependencies in iOS projects. It’s a practical guide for developers looking to optimize their workflow with the right tools.

  • Swift Package Manager (SPM): Used for managing Swift dependencies and libraries.
  • CocoaPods: A widely used dependency manager for iOS projects. Example: pod install
FdQhCcP pgrty1sdSRrtkSvidNWzSYNlhImm5ae T7wwWEo3Hjzo7z8 6plHuJpLoYLi38JT zeudVz0bs

UI frameworks for iOS projects:

Choosing the right UI framework is pivotal in iOS app development. This section covers the various UI frameworks available, such as Storyboard and SwiftUI, and their impact on app development. It’s a comprehensive look at these tools, helping developers understand their features and how they can enhance their projects.

1. Storyboard

Storyboard is a visual interface builder available in Xcode, Apple’s integrated development environment for iOS app development.

  • It provides a graphical representation of the UI, simplifying collaboration between designers and developers.
  • Using a drag-and-drop interface, developers can easily add UI components and define their properties within Storyboard.
6ZX43yW0Ru6XdoAxAH8ucBw5HEqjwV6pl3CfokpKLDgZebqEcxTkj04HEGL

2. SwiftUI

SwiftUI, introduced by Apple starting with iOS 13, is a modern UI framework. It employs a declarative syntax, enabling developers to define UI and behavior using clear, expressive Swift code.

  • With SwiftUI, developers specify the UI’s appearance and behavior, and the framework handles the rendering accordingly.
  • During development, SwiftUI offers immediate feedback, facilitating rapid iteration and adjustments.

What are the targets in Xcode?

In Xcode, targets are representations of applications or specific units of work within a project. They encapsulate configurations, settings, and build phases, enabling specific building, testing, and running approaches for your application.

A UI Test Bundle target, on the other hand, is specifically utilized for composing and executing UI tests on iOS, macOS, or other Apple platform applications.

Adding UI Test Bundle target for a project:

  • Open the project navigator and select your project. Look for the plus (+) icon at the bottom and click on it.
  • From the “Choose a template for your new target” window, scroll down to find and select “UI Testing Bundle.”
  • Provide a name for the UI Test target and configure any necessary options for the target.
  • After setting up the target, click on “Finish” to create the UI Test Bundle target.
nNHjSDvAqxKvMLjNO1zwhTCeb2BTIV1 v7cyCjcw92KnDpThWEDy IAFf6Ha3qYwNm 5irDPsm3om2AyIc89PWDpIWpBCfOXuCmED6eO7py14xfW7 uw3kVSy br32pjVJwXHkHkP4iq3btMkpakms

XCUITest APIs:

The XCUITest APIs are a powerful framework that allows you to automate user interface tests on iOS apps. They enable you to perform UI interactions and validate app behavior seamlessly, making your testing process robust and efficient. Let’s explore some XCUITest APIs that can help you achieve this goal.

  1. XCUIApplication: 

This API represents the tested application instance. It grants access to the application’s UI elements and facilitates actions like launching, monitoring, and terminating the app.

let app = XCUIApplication()
app.launch() // Launching application

Want to learn UI Automation and API Testing? Master Cypress for seamless UI and API testing! Enroll now!

DigmfP 6To19v42Fkblub8J5jJtcwySAoZaJZQXz37UAcewj1sZwJRWJVDnI0SMC3KRSf uoAWmEB2lm1YhRUroXwGNZXRKq

NOTE: In cases where the source code is unavailable, retrieving the Bundle Identifier is possible through the app’s App Store listing or using tools like Apple’s xcrun simctl command. This information allows for the continuation of automation even without direct access to the app’s source code.

app = XCUIApplication(bundleIdentifier: "com.example.yourapp")
app.launch()
  1. XCUIElement:

XCUIElement serves as the representation of various UI elements within an iOS application. These elements encompass buttons, labels, text fields, and more, offering methods to facilitate interactions with these elements throughout UI testing.

JqZuNol 0OSgrRYIXrO3CW c6WRZ23e8b2YXGcN BGJzlXVfELxOBtPjpaWAeksMmzmceLHafR e6zgh ubJz9F0sHkIBP8rYvTqs uKR1W8hKXo6D0TjNY973eYgxISVX exTsVutgPdoC 2AqSyGg
  1. XCUIElementQuery

XCUIElementQuery serves as a tool to locate and engage with UI elements within the tested application. This query functionality allows the identification of elements based on specific criteria like element type, accessibility identifier, label, value, and more, facilitating efficient element retrieval during testing.

  1. XCUIElement Actions:
uoPwDuRQ99amPEYbA8 N9sLSfcBrtFrb1HRaH7 CIZSenfHBjcI7bHeVeUuveIm2A9sHkWTTGsKONWKbF qfJptVflQuF7U x0GRVsLYCA9y 7Y0300uLwmRp3683Do3addf4tP2Xuf19zw9cB6UEIA

5. XCUIElement Attributes:

XCUIElement Attributes pertain to the properties or characteristics of a UI element within an iOS application. These attributes are accessible and modifiable when creating UI tests using XCUITest, enabling manipulation and verification during the testing process.

xl1AbO1 Dy rRdbhTeB8bAx 7q9aZ2Es9 eo0LCsybJrTYBo7Hm39Qd

XCTestCase class:

When initializing a UI Testing Bundle, Xcode automatically generates and organizes various files and directories within our project to facilitate effective management of UI tests:

  • UITest target: Adding a UI Testing Bundle creates a distinct target within our project dedicated to UI testing. This target possesses its own configurations and settings, separate from the main app’s target.
  • UITest folder: Upon creation, Xcode introduces a new group in the project’s file navigator, typically named after the UITest target. This group consolidates all files related to our UI tests. Within this group, subdirectories and files are organized.
  • UITest XCTestCase Classes: Xcode generates XCTestCase classes tailored for our UI tests. These classes house the test methods defining our UI test cases. Additional XCTestCase classes can be created as required.
  • Test Case Class: XCTestCase serves as the foundational class for our test cases. We establish subclasses of XCTestCase to define individual test classes, enabling the specification of various test scenarios.
  • Setup and Teardown: XCTestCase offers methods to facilitate the setup and teardown of the test environment. The “setUp()” method is run before every test method, while tearDown() is executed after each test method, allowing for essential setup and cleanup operations.
  • Test Methods: Test classes comprise test methods that should begin with the word “test.” These methods contain the test logic, encompassing steps and verification procedures essential for assessing the functionality being tested.

Finding & Interacting with XCUIElements:

Apple’s Xcode IDE includes the Accessibility Inspector, a tool designed to examine and engage with the accessibility attributes of UI elements within an iOS application. It proves invaluable in identifying elements for interaction within XCUITest scripts.

To utilize the Accessibility Inspector for XCUITest:

  1. Open your project in Xcode.
  2. Run the application by selecting a device (simulator or real device) from the menu and clicking on the Play icon located in the top-left window.”
  3. Open the ‘Xcode’ menu. Navigate to ‘Open Developer Tool’. Choose ‘Accessibility Inspector.
hhprlDS9sXvAPSC7XZ KLzQi1oo4JRWLZJS3geFB5 FWIQc8YzBb8HRfo2GsfYw7AknRYd5SZVaWmnMstjwkcTyQDhppAi3kxbyCocLzySDCGeWLPbhORUI gvVhEZwCYixee8hABUs lUZmc00bbUQ
  1. When using the Accessibility Inspector tool, locate the icon within the interface and click on it. Hovering over the UI elements in our app allows for their inspection. This action reveals detailed information about the selected element, presenting data such as its accessibility label, identifier, type, and other associated attributes.
mjm6ISedoBVekicmqXKHYQAwalFXiovD9NLNVPo3MV2Hzt1AP4yQTaObASGNfAeZiTiyys2gTjrQELuo 4VhXd4lBbiBKdKYDjroajNxLXocUgwHIq058gwvtOHh1LSMtfwRIKaV5l3x520Dv4R LYI
  1. Utilizing Identified Elements in XCUITest involves integrating these elements into our test scripts. Below is an example demonstrating the usage of the XCUIElement class in Swift to interact with a specific element:
let app = XCUIApplication()
app.textFields["userInfo"].typeText("test")
app.secureTextFields["password"].typeText("password")
app.buttons["login"].tap()

Accessibility labels and identifiers serve as highly dependable means for element identification, known for their stability across app versions due to their lower probability of alteration.

How to Execute Tests?

In each test class, there are diamond-shaped play buttons corresponding to individual UI test methods as well as the entire class (as shown in the screenshot below). Clicking the diamond button beside a method triggers the execution of that specific test method. Alternatively, clicking the diamond button next to the class name initiates the execution of the entire class, running all methods sequentially.

Lhpr3wXuYr7ab8a2cc3LZAcMPNAZKA7Ok2K7ECZeu4Bf8t96HHzTi7C2iFcxhkp lmK Jx2n flF34WxS8aFmKDjpu7shMijWoFM K7wqq4Q8GzPfg Zl7bgJlGQi W1koVmoSNl72QTlOgrCsqil8

An alternative method to execute test methods and classes is through the Test Navigator. Here, you’ll find similar diamond-shaped buttons adjacent to both test methods and class names, providing another means to initiate the execution of individual methods or entire classes.

5LRjNN1fqI45sP0RFVorj4P7NZzBG2RjMmmWKeVMFD8a9IqXEbndSP FdpnqofxjC46ugr wgkBRFi5iqKh C9ZRSJVG VCXROh1n5Ka IuvQ2ioHn2s51vVN9zgoHoy7Ygof xuMR

Conclusion:

In conclusion, the adoption of XCUITest as the primary automation tool for iOS applications emerges as a strategic imperative. With iOS commanding a substantial share of the global smartphone market, the native advantages offered by XCUITest, including seamless integration, optimized user experiences, and Apple’s backing, outweigh potential reservations. Dispelling myths and exploring its robust features, XCUITest stands out as a reliable choice, ensuring high-performance testing, security, and long-term viability in the dynamic realm of iOS development. By embracing XCUITest, you can efficiently navigate the intricacies of UI testing, fostering a seamless and reliable user experience on iPhones and iPads.

Written by

Shishir is a seasoned Quality Assurance professional with over 8 years of expertise specializing in automation testing. Throughout his career, he has meticulously ensured the quality and reliability of software products across various industries. When not immersed in the world of testing frameworks and code, Shishir indulges his passion for travel, exploring new destinations, and capturing memorable moments through his lens as an avid photographer. His unique blend of technical proficiency and creative flair makes him a valuable asset in both the digital and real-world landscapes.

Leave a Reply

Your email address will not be published.

Related Posts

Testing Courses at Thrive EdSchool

Advertisement (Know More)

Get Top Community News

    Top Event and other The Test Tribe updates to your Inbox.

     

    Categories

    Tags