Unit Testing in iOS and TDD

This post is about Unit testing in iOS. And Unit testing consists in creating code that checks the functionality of your code.

TDD says:

1. Program the tests.

2. Program the code that is tested.

This is very nice but, how can I do that?

Well, the easiest way to start is working on your new implementations. Try to divide those in little classes that can be tested individually and then do a Unit test for that. You should be going through this steps.

1. First of all, program a test for one use case. It will always fail because there is no code trying to pass it just yet. For example, for a new implementation you can test for the most common case.

2.Then start programming so the test is passed. Don’t focus on refactoring or lose time cleaning code, just pass the test the easiest way.

3. Once the test is passed, refactor: Clean and restrucure your code, remove repeated lines, but you will automatically know if the code is still working as the test needs to be passed again.

Unit Testing in iOS: Real example

First of all if you want to use Unit Testing in iOS I recommend to you to use Kiwi. You will see in the Github project how to install it but the easiest way is using Cocoapods.

Create your project

Starting a project to do Unit testing in iOS

Remember to check “Include unit tests”.

Then and edit your Podfile:

See that we are installing Kiwi for our Test Target only.

Kiwi syntax

Kiwi is a BDD — Behavior Driven Development – and this means that the syntax is a bit different of what we expect. It says with common language what code should do. If you’ve used rspec you will already know the syntax:

It’s all block based and you should read the block from the outside to the inside. In the code above we see two test cases:

– Team, when newly created, should have a name.

– Team, when newly created, should have 11 players.

Mocks and stubs

Unit testing is based is in Expectation. We expect code to do things. Most of the times we will say in our test what we expect and sometimes we will need to hard-code the expectations.

For example, we are testing a class that saves a tweet. Let’s call this class TweetSaveManager. This class when save a tweet check if somebody is mentioned and send him an email. TweetSaveManager saves the tweet but don’t send emails so we will delegate the sending email task to SendMailManager. SendMailManager will have another unit test that covers it functionality so in TweetSaveManager we will expect that sending email just works.

We will use stubs to prevent email doing the send like this:

Mocks are like stubs but adds an expectation that this call will be done. We are now testing that this method is called and if is not called this will make the test fail.

In latest example we should verify that we send the email.

This post will continue in a second part with some utilities we use in Unit Testing in iOS. Hope you’ve enjoyed reading!

Hugs from lafosca

No Comments

Post a Comment