At WWDC 2017, there was an amazing talk on engineering for testability which focuses on the importance of the quality of the test code along with the app code. The talk introduced various way we can improve the testability of apps by writing great test code. The most important bit was a second part where the tips on improving the scalability of UI tests have been shared. In this post, we will see those tips shared by Apple engineers. Remember, this is not just a copy-paste of the talk presented at WWDC; this post also has some real life examples with a demo project on GitHub, Scalable-XCUITest, to prove those points.

What Is Scalable Test Code?

The test code is as important as the app code even though it's not being executed in production. We should definitely make our app testable, but also put some effort into making the test code more scalable. The benefits of scalable test code are

Running our tests faster.

Making our tests more readable, even for non-technical people.

Organizing the test code in a better way to avoid duplication.

Making it easy to add new test cases.

Example App

Let's explore some of the techniques shared by Apple engineers to make the test code scalable with an example application, Scalable-XCUITest. This app has buttons with six different colors: RED, GREEN, BLUE, BLACK, GRAY, and YELLOW. This is a very simple app, but imagine that we have to test a few things, like

Again, to test the RGB and non-RGB values, we have to almost repeat the same things. You can have a look at the test class Non_Scalable_XCUITestUITests.swifthere and guess how messy it is. We can definitely make it better by using the techniques described in the talk.

Tips for Writing Scalable Xcuitest Tests

Here are some tips shared to make tests scalable, maintainable, and faster by using some common object-oriented principles like abstraction and encapsulation. Let's go through some of these techniques.

Abstract Xcuielement Query

If there is a situation where we are using a XCUIElement query multiple times, store it in a variable. In the example above, we are tapping a button six times, but only thing changing is the color of the button. We can easily wrap this into the method.

Now our test to tap on RBG and non-RBG buttons is more readable and extendable.

Sprinkle Xctactivities for Better Test Reporting

Activities are a way to organize actions into groups by giving a meaningful name so XCTest results will use that activity name in the result, making it more readable. You can read more about activities in Apple's official documentation here. In our example, we can sprinkle in XCTActivities and make more readable test reports.