Dive into UITesting using XCTest in Swift

Tolga Taner
2 min readFeb 15, 2021

--

Photo by Christina @ wocintechchat.com on Unsplash

Writing User Interface Testing is different from Unit Testing from some aspect. When we write User Interface Testing, we actually tell to XCUIElements to the screen swiping, the button tap, the keyboard tap that is shortly user interactions rather than performing programmatic tests against a certain API.

Preparing

Before diving deeply, If you don’t have any test scheme, please apply those instructions step by step.

File > New > Target.. in Xcode and select a “UI testing bundle”, and then edit your apps scheme to run your UI tests when testing, by going to Product > Scheme > Edit Scheme.. in Xcode and adding your UI testing bundle under “Test”

Let’s Dive

Our aim is user login flow testing to type both username textfield, password textfield to test keyword, tap Done button in LoginViewController and then navigate WelcomeViewController respectively.

Main.storyboard

First, we need to define an accessibility identifier of UIElement that is corresponding to XCUIElements.

Now, we define a XCUIApplication type property to accessing all XCUIElements that is called app.

setUp()

This method is used for initializing app property and setting up some configurations such as setting false to continueAfterFailure is for when we encounter a failure case our test should be stopped cause of test cost, adding launch argument to adjustment of the test state.

testNavigateToWelcomeViewController()

Before we realize expected user interactions, we need to call launch() method.After that, we can check used elements are dislayed after app is launching to using XCTAssertTrue().As we can see in the extension, app property has XCUIElement type property such as: Buttons, TextFields, SecureTextFields etc.We can access one of them for using accessibility identifiers.

For showing all interactions as we expect, we need to uncheck all options inside > Simulator > I/O > Keyboard..

Resetting State

Finally, we completed all steps.

Complete project is here, https://github.com/TolgaTaner/UITestExample

Follow me if you enjoy to read 👋

--

--