Introduction to TDD in Swift

Less bug. No more headache.

image taken from here

My first writing in English, so let’s begin 😂

In this writing, I’ll try to explain to you about TDD (Test Driven Development). So, what is that?

TDD is a software development technique which require you to write the test first, then write actual code to pass that test which you’ve wrote before, only. If there’s another condition that must be handled by your code, or you’ll add a new feature to your software, or you’ll fix the bug, that’s so simple. Just write your different test again, then write your code to pass that test again.

So, your development cycle will be like this if you implementing TDD

  1. Writing and run the tests
  2. Coding
  3. Refactoring
  4. Re-run the tests
  5. Back to number 1 if your development phase hasn’t been completed.

Make TDD more Swifty

Implementing TDD in your Swift project (iOS apps or macOS apps) is quite simple. You’ll only to write the class that inherits from XCTestCase class, define your testcase, then run that test. I’ll show you how to make the tests, and for this example, I’ll do all of this tests with Xcode Playground, for the sake of simplicity 😁.

In this example, I’ll create the algorithm that solve this simple problem.

You’re game developer. You will build a simple fighter game which involve 2 fighters to brawl each other. Every fighter can attacking his opponent, and have a life meter and damage power. If fighter gets attacked, his life meter reduced by his opponent’s damage power.

Example objects

Cena 570 60
RKO 510 65

Column 1 is fighter’s name, column 2 is fighter’s life meter and the last one is fighter’s damage power

Step 1

Define the Fighter

Step 2

Define how the fighter attacking each other, and get wounded 😂

We will write our first test, yeay. Let’s write the test class first, and write our test method to attack each other

Modify your Player.swift first, and add this method

Now write your test case at testFighterAttackingEachOther() method as follows

This test is used to ensure the opponent’s life meter has been reduced by attacker’s damage power.

Then, XCAssert method is used to check the condition after running the test, if the result is true , you passed the test, and vice-versa.

To run the tests, add following lines to your playground

Then, run your playground, and you’ll get assert failed, because the test has failed

To make your code passed that test, you must modify attack(opponent:) at Player class

So run your test again

Horray! Your test has been passed 😁

What’s next?

After this brief introduction to TDD, i hope you can implement it in your real Swift projects (no need to use playground anymore), and understand about how to writing unit test and run the tests. If there’s any mistakes or something that can’t be understood, let me know in the comments. Cheers.