iOS Testing Guide

Asynchronous Promise

Rajai Kumar
Nerd For Tech
Published in
3 min readMar 2, 2021

--

Testing asynchronous code is not very straightforward.

What’s the issue?

In general, a test is over when the function returns. Using this theory, all asynchronous code will be skipped, bcoz the test will be over before the code starts.

What’s the solution?

A promise. We need to tell the system to wait for a particular period of time or till we fulfil the promise.

How it’s done?

Here what we are calling as promise is actually an expectation-XCTestExpectation, but promise is the widely used term in the S/W industry, just google and see for yourself.

An expectation is set using the expectation(description:) method with a description explaining what the expectation is.

The fulfill() method is called when the asynchronous code is done.

Then use the waitForExpectations(timeout:) to keep it going until the timeout interval is done, or the expectation is fulfilled.

Let’s see some code.

Import the project you are going to test.

We are going to use URLSession for this example. You can use your own Class/Struct or any third party library like AlomaFire for this purpose.

Write the setUp() and tearDown()methods.

Let’s write the test without promise to see how it fails. Test will always fail because the code inside the completion handler didn’t even start when XCTAssertEqual() method was called. Use a breakpoint or print statement to verify this.

It’s time to use the methods we saw first to write our test. We will be using the given - when - then format to write this test case, if you want to know more about this format, then take a look at iOS: behavioural testing- Given When Then in UI & Unit testing.

Now you would be able to see that the XCTAssertEqual() method was called either after 3 seconds or after the fulfill() method was called. Check this using a breakpoint.

That’s it guys, it’s time for me to leave.

👾 Gist

🙏🏽 Thanks- Ray Wenderlich, Paul Hudson, ray.so

--

--

Rajai Kumar
Nerd For Tech

I’m a workaholic iOS developer. I focus a lot on UX and product efficiancy.