Join CTO Moataz Soliman as he explores the potential impact poor performance can have on your bottom line. πŸ‘‰ Register Today

ebook icon

Engineering

General

Test-Driven Development Tutorial for iOS

You're working on a new feature and suddenly an old feature stops working even though you wrote unit tests. Or you're refactoring legacy code and you think it's done, but suddenly you find a lot of bugs. So you go back, you make the fixes, and you think it's done, but then you find more bugs. You repeat and you think it's done every time, but the same thing happens, every time.

You have to write tests to make sure that your product is working, and the only way to prove it's working is through testing. And you need to be testing constantly in order to catch regression errors so that you can add new features without breaking existing ones.

So you're working on software with tests and yet you have a bug in the logic that was already covered by those tests?


Your test results have given you a false positive about your software.

Test-Driven Development (TDD) is the best solution for this problem. TDD is not unit testing. Unit testing is writing code to test our code. So first, we write our code, and then write unit tests to verify our logic that we just wrote. But TDD is totally different. With TDD, you write the tests first before writing the code.

TDD forces you to see your failing tests, which shows you how to turn them into green when you fix these failed tests.

‍

Test-driven development definition

TDD is a development technique where you must first write a test that fails, then write code to get it working, and finally you will need to refactor the code to be as simple as possible.

‍

TDD Test Driven Development Unit Test Process

‍

In many cases, writing automated tests is seen as not real work and boring compared to building new features. TDD, however, turns testing into a design activity. We use the tests we write to clarify our ideas about what we want the code to do. It also keeps code as simple as possible so it’s easier to understand and modify, especially since developers spend more time reading code than writing it.

As we develop in TDD, it gives us feedback about the quality of both its implementation (does it work) and design (is it well structured).

Each level of tests should answer specific questions about our code.

1. End-to-End Tests: Does the whole system work?
2. Integration Tests: Do our objects work with each other correctly?
3. Unit Tests: Do our objects do the right thing?

‍

TDD process

First we need to write user stories, which describe the system in detail. User stories describe business features in a convenient way for technical teams so that they can work on them easily.

More important than user stories is their acceptance criteria, which you use to validate that each story is done or not. Solid tests start from writing solid acceptance criteria.

‍

TDD Test Driven Development Unit Test Process

‍

1. For each acceptance criteria, you need to write a failed end-to-end test.

2. You need to write code to make this end-to-end test pass, by writing failed integration tests that describe how your objects will interact with each other.

3. For every class, you need to write a failed unit test to test the output of each single unit.

4. Then you need to write actual code to make the unit tests pass for all classes, and the integration tests and end-to-end tests pass for all acceptance criteria.

‍

TDD Test Driven Development User Story

‍

Example TDD project

We are going to build an app that shows a list of movies (name and rating). Even a small story (feature) like this is too large to write in one go, so we need to figure out roughly the steps we might take to get there.

Here are all the features required for our sample application:

Show a list of movies. ??

Here is our user story:

As a user, I want to be able to see a list view so that I can choose my next movie.

And here is our acceptance criteria:

The app should show the name and rating of each movie.

Now we can start. ?

‍

Setting up our project

First, you need to create a single view project with Unit Tests and UI Tests targets:

‍

TDD Test Driven Development Sample Project

‍

Most App Store apps communicate with the cloud, fetch data, and show it to the user. In order to work on a solid base on which to build features, you need to simulate the two sides that will communicate with your system. The first side is user interaction, which can be done using UI tests that trigger user events as if from an actual user. As for the cloud, you can use a framework like Swifter to simulate server requests.

‍

Swifter wrapper

Swifter is a tool that will help you stub application requests and return the desired response to facilitate testing and prevent test flakiness.

‍

TDD Test Driven Development Sample Project Swifter

‍

We are going to make a wrapper class over Swifter to facilitate stubbing network requests.

We will create a class called HTTPDynamicStubs, which will provide a public method. You just need to add the URL you want to stub and the link to the JSON file (more on this later) to be returned when your app requests this API and the HTTPMethod.

Before every test case, all you need to do is create an instance from HTTPDynamicStubs and call a setup method, which will start the server and change the base URL to localhost. To remove stubs, tearDown the HTTPDynamicStubs after each test.

‍


‍
Inside each test case, you can stub requests and return the JSON you need.

‍


‍

User story

As I said before, solid TDD starts from writing good user stories with clear acceptance criteria. We will represent each user story with an end-to-end UI test.

Note: You cannot write end-to-end tests for everything. If you do, you'll end up with very slow tests that you won't even be able to run every time.

To recap, here's our user story:

As a user, I want to be able to see a list view so that I can choose my next movie.

If you would like to follow along with this tutorial, I prepared a JSON file that contains a list of movies that will help us test this user story.

‍


‍

Writing our end-to-end test

According to our user story, a user will need to open the application and see the list of movies. According to our acceptance criteria, each movie will have a name and rating. So I need to write a test that will launch the application and make sure that there is a tableView filled with movies, with the name and rating of each movie.

‍


‍

Line 1: Stub the network request for movies and return the mock JSON file.

Lines 3, 4, 5: Assert on each movie name and rating inside UITableView.

After writing the end-to-end test, you should make the test fail. Read the assertion messages and ask yourself if you really understand the problems from reading the messages. If not, rewrite more meaningful messages. This will help you identify problems later when you change some code and this test fails.

‍

Acceptance criteria

Now it’s time to write the integration test for our acceptance criteria. To recap, here is our acceptance criteria:

The app should show the name and rating of each movie.

When writing integration tests, imagine the components of your system that will be responsible for implementing this part of the feature, and how they will communicate with each other.

Integration tests exclude the UI component and only test functionality after the UI layer (it’s supposed to be fast). If you are going to use an MVP architectural pattern in your app, your integration tests will make sure that the presentation layer will communicate properly with the model layer.

So, we will trigger an action from the presentation layer, stub the network request, and assert the callback to make sure that collaboration works between the presentation, model, and network layers.

‍

Writing our integration test

With MVP, View will be responsible for displaying the data and listening to user interactions while Model will be responsible for defining the business logic and fetching, updating, and inserting the data. Presenter will make sure to decouple interaction between Model and View, and act as the communication layer between them.

‍

TDD Test Driven Development UML

‍
Now I need to imagine how many objects I will have, the responsibility of each object, and how they will interact with each other.

So I think I will need MovieListPresenter, which will be responsible for asking the MovieListModel to fetch the movies. MovieListModel will fetch them through the network layer, receive the JSON, parse the JSON, and return them to the presenter.

‍


‍

This integration test will ask MoviesListPresenter to fetch movies. It is supposed to receive a callback when it successfully receives a response or the request fails. So this test needs to mock the network layer and simulate that an actual request came from the cloud.

Steps:

1. I need to create a mock network layer, which will return specific responses so I can assert the returned data from Presenter.

2.I need to create MoviesListModel, which will be responsible for calling the network layer, receiving a response, and parsing the data.

3. Presenter will use Model to fetch movies and reformat the movies to be displayed on UI components.

Note: Here I should not be able to receive objects from MoviesListPresenter. It’s only supposed to return primitive data types to totally isolate Model from View.

‍

Network layer

For the sake of this example project, we are not going to implement a complete network layer. We will build the most simple block of code to execute a GET request and return a response.

‍


‍

For this tutorial, we are not going to write tests for this class, but it’s doable using a third-party library like OHTTPStubs.

‍

Writing unit tests and writing code to make them pass

After finishing the design and writing the integration test, we will go through each object and write unit tests for every class, and then write code to make these tests pass.

‍

MoviesListModel

MoviesListModel will use the network layer to fetch and parse data. In order to test MovieListModel, we need to stub network requests. So we need to implement a mock object for the network layer that will take the desired response as a parameter in initialization and return it inside a callback.

‍


‍

I expect to fetch movies on MoviesListModel and return the movies in the callback. So the test should be like this:

‍


‍

MoviesListModelDelegateMock is a helper class that will help me to assert movie values.

‍


‍

Finally, we are going to write the actual code. Let’s implement MoviesListModel to make its tests pass.

‍


‍

We will call the network layer, parse the returned object, then return it through the delegate.

‍

Let ’s run MovieListModelTests again.

Congratulations, your first test passed! ?

Note: According to the Single Responsibility Principle, MovieListModel is doing two jobs: fetching data from the network and parsing it. So we need to separate the parsing functionality into another class.

‍

MovieParser

Once again, we will first create tests for MovieParser and watch them fail, then implement the parser. After finishing the refactor, you will need to run MovieListModelTests again to make sure that everything is working fine.

‍

MoviesListPresenter

We will begin with writing tests inside MoviesListPresenterTests. First, we will need to create MoviesListModelMock to stub fetching movies so that we can easily test only MoviesListPresenter.

‍


‍

Next, we will pass the mock movies to MoviesListModel and pass it as a parameter to MoviesListPresenter. Then, assert on Presenter methods.

‍


‍

Now, we need to implement the MoviesListPresenter class to make the tests green.

‍

Writing code to make our integration test pass

Now that we've written failed unit tests and made them pass, we can write our code to make the integration test pass.

We need to make an initializer that will take MoviesListModel as a parameter to allow Presenter to use it and make Presenter be its delegate.

‍


‍
The presenter will fetch movies from the model.

‍


‍

ViewController needs to display data inside UIComponents and Presenter should not expose Model to the UI. So we need to create an abstraction layer to hide Model from our UI.

‍


‍

Then we can run all our unit tests and the integration test. Everything should pass. βœ…

The final thing we need to do is make the end-to-end test pass.

‍

Writing code to make our end-to-end test pass

After implementing the UI, you will need to create an instance from MoviesListPresenter inside MoviesListViewController and implement its delegate.

‍


‍

Then, run your end-to-end test. Everything should pass. ?

‍

Conclusion

If you have multiple acceptance criteria, you will need to write more integration tests for each of them to complete your user story.

In this tutorial, you learned how to implement a complete user story with solid tests without the need for backend integration. To make sure you are integrated correctly with the cloud, you will need a copy of the end-to-end test to actually run on a testing account.

Now thanks to TDD, after you develop more features in this project, if one of the above tests fail, you'll have a quick hint about which part in the code has a problem.

You can find the complete project here: Sample TDD Project.

Want to try our latest AI features?
Sign up to the closed beta now
Thank you! We'll contact you once a spot opens up.
Oops! Something went wrong while submitting the form.

Learn more:

‍

Instabug empowers mobile teams to maintain industry-leading apps with mobile-focused, user-centric stability and performance monitoring.

Visit our sandbox or book a demo to see how Instabug can help your app

Seeing is Believing, Start Your 14-Day Free Trial

In less than a minute, integrate the Instabug SDK for iOS, Android, React Native, Xamarin, Cordova, Flutter, and Unity mobile apps