Page Object Pattern for iOS UI Testing

Hasancan Akgündüz
2 min readDec 10, 2021

--

Before talking about page object pattern, first let’s move app launch code to a common place and share it in all our uitests like this:

All UI tests are derived from MyAppXCTestCase so we do not have to add app launch code into every UI test classes.

Now, let’s talk about page object pattern with an example ui test:

We have two views: FirstView and SecondView. The UI test verifies the elements of FirstView and taps on the button of FirstView and later verifies the visibility and elements of the SecondView.

This code has some problems. Firstly, it is hard to read. Secondly, it is not reusable. Another problem is, it has hard coded identifiers around.

To solve the reusability and readability problems, we can alter the test code according to page object pattern. For the hard coded identifiers, we can create enums with the static identifiers:

I named the protocol View rather than Page just to be compatible with SwiftUI naming, you can name as per your taste. For every view, we create a struct conforming to View and create small modularized ui test functions. These functions return itself or another View to allow us chain the functions. Also, every View has its own accessibility identifiers enum.

Here’s how we use this pattern to write ui tests:

It is much more readable, reusable and maintainable.

--

--