iOS – Unit Testing


This post will talk briefly about setting up a bare-bones iOS app to illustrate what unit testing is all about and how to utilize the XCTest Framework for writing your own tests.

Imagine that you are writing a method to validate US and Canadian ZIP codes (or postal codes, as they’re called in Canada). In the US, ZIP codes are 5-digits long. Things like 77335, 06226, 29631 and so on.

In Canada, postal codes are typically written using 6 characters, with a space after the first three characters, like so:


In the above code, L is a letter from the alphabet and N is a number or digit from 0-9. So Canadian postal codes can look like A2K 4L8, K7G 5T9, M2N 6P8 and so on. To make things more interesting, there are some additional rules about what letters are allowed (or rather not allowed) at various positions:

  • The first letter cannot be W or Z.
  • The letters D F I O Q U are not allowed at any location.

There might be more rules, but we’ll stop here. You get the idea where this is going. We’ll need to write a method that receives a user input string and then parses the string to make sure all these rules are met (for both US and Canada). Let’s assume you cook up the following class method somewhere in your model:

If the user enters the correct ZIP code, this method should return YES, otherwise it should return NO.

Once you finish developing this method, you simply go to the test section of your project and start adding in various test cases to check your method. There are some who maintain that these test cases should be written even before you create the above method – we will not argue about what approach is best – do whatever works for you.

For simplicity, this post only talks about the following testing methods, which suffice for our purpose here:

  • XCTAssertTrue( something_that_should_be_true, @”optional message displayed when that something is false” )
  • XCTAssertFalse (something_that_should_be_false, @”optional message displayed when that something is true” )

This is how you use them in the code (all you need is to include the header file of your model class in the test case file):

You can add as many tests you like in this file. To run these tests, use

Product —> Test (or the keyboard shortcut  Command + U)

Xcode will run all your tests and place cute little check signs next to each test to let you know which tests pass and which tests fail.

That’s it! Isn’t unit testing cool? Now that I’ve wrapped my head around the basics, I will start adding unit tests to several of my iOS projects.

Leave a Reply

Your email address will not be published. Required fields are marked *