Some top reasons to write unit test cases with Swift

Learn the prime reasons to write unit test cases with Swift for your iOS app.

Unit tests are awesome. They not only improve the overall quality of your code but also make it easier for you to test individual pieces of your app without having to manually run your app.

Turn your idea into an app, fast with our extensive iOS solution!!!

Given Apple’s extensive support for unit tests in Xcode and Swift, it’s surprising that so few iOS developers write unit tests. It is my hope that after completing this simple tutorial, you will see just how easy it to get started with unit tests in Swift.

Reasons to Write Unit Test Cases With Swift

  1. Its Reduce Bugs in New Features.
  2. Its Reduce Bugs in Existing Features.
  3. Permit Refactoring.
  4. It Reduces the Cost of Change.
  5. Improve Design.
  6. Constrain Features.
  7. Defend Against Other Programmers.
  8. Testing Forces You to Slow Down and Think.

Tests Reduce fright one of the largest frights that programmers encounter is making a alter to a piece of code and not knowing what is going to break.

1. Setting up your project

One of the largest challenges to Unit Testing in Swift was the initial setup. Before Swift 2, you either had to create everything public or consider including all your files to the testing target.

  • Starting with a new project

Firstly, we are going to build a blank iOS project. You will desire to have the include unit tests checkbox checked.

write unit test cases with Swift

  • I already have a project, and I need to include tests

Navigate to File > New > Target.

Choose iOS Unit Testing Bundle.

Click Next.

2. Create an internal Class

Build a very simple internal Model Object in your project with a sample function. You don’t add Car to test target “UnitTestTests” and not making the class or your methods public.

write unit test cases with Swift

3. Apple’s Example Test Case

When your app is setup for testing, you will observe a folder, UnitTestTests, with your tests in it. Xcode sets up a template, UnitTestTests.swift, test for you.

Each test case you mark will import XCTest framework.

@testable import declaration is an additional import declaration. When you exploit @testable, there is no demand to give any files in your application membership into your test target.

To build a unit test, you will be subclassing a thing called an XCTestCase(class UnitTestTests: XCTestCase) .

Try putting your mouse cursor over them. They are an inline button that runs your test. If you float over the diamond next to it, you can tap to run the test. Your app and its test target will find built, the test will run, and you will observe the test achieved notification.

This example test isn’t mostly helpful. It doesn’t test anything. It just offers you a template to recognize how to write tests. To observe the real power of unit tests, we want to create something to test.

4. Setup and use Car class

Now start with an easy code to manage our cars:

// Car.swift
import Foundation
class Car {
 var miles = 0
 var type: CarType
 var transmissionMode: CarTransmissionMode
 init(type:CarType, transmissionMode:CarTransmissionMode){
 self.type = type
 self.transmissionMode = transmissionMode
 func start(minutes: Int) {
 var speed = 0
 if self.type == .Economy && self.transmissionMode == .Drive {
 speed = 35
 if self.type == .OffRoad && self.transmissionMode == .Drive {
 speed = 50
 if self.type == .Sport && self.transmissionMode == .Drive {
 speed = 70
 self.miles = speed * (minutes / 60)

enum CarType {
 case Economy
 case OffRoad
 case Sport
enum CarTransmissionMode {
 case Park
 case Reverse
 case Neutral
 case Drive

We can begin and use a Car object “Ferrari” in a ViewController:

// ViewController.swift
import UIKit
class ViewController: UIViewController {
 override func viewDidLoad() {
 let ferrari = Car(type: .Sport, transmissionMode: .Drive)
 ferrari.start(minutes: 120)
 print(ferrari.miles) // => 140
 override func didReceiveMemoryWarning() {

Ok, it’s not horribly motivating but will be sufficient for our first unit test.

5. Creating a Car Unit Test Swift Case

To create a new unit case in iOS:

Navigate to File

New File

Then choose Unit Test Case Class.

In choose options for your new file, type class name: CarTests and press Next

write unit test cases with Swift

write unit test cases with SwiftWhen you click on Next, you will be taken to another screen where you will choose the new CarTests file should leave. Ensure you build it in your Unit Tests Group, and also ensure it is only a part of the unit test target, not the app target.

It’s another test case, but this time it’s for testing our Car Class.

// CarTests.swift
import XCTest
class CarTests: XCTestCase {
 override func setUp() {
 override func tearDown() {
 func testExample() {
 // This is an example of a functional test case.
 func testPerformanceExample() {
 // This is an example of a performance test case.
 self.measure {
 // Put the code you want to measure the time of here.

6. Customize CarTests

  • utilize @testable to import your application

import XCTest
@testable import UnitTest

import XCTest
@testable import UnitTest

You perform this before you declare your test case class, CarTests.

  • State the things you want to test

We will state them as absolutely unwrapped optional (!) because by the time our test case has set them up, we can guarantee they will be started and ready to test one another. Placing a! In Swift, the front of a variable means your code can imagine the variable to forever have a value when you use it.

class CarTests: XCTestCase {
 var ferrari:Car!
 var jeep:Car!
 var honda:Car!
  • Override the setup() method

To setup out Car in the test, we will overrule the setup() method. The Car will get setup with their equivalent types and transmission mode.

override func setUp() {
 ferrari = Car(type: .Sport, transmissionMode: .Drive)
 jeep = Car(type: .OffRoad, transmissionMode: .Drive)
 honda = Car(type: .Economy, transmissionMode: .Park)
  • Override the tearDown() method

We also desire to ensure we clear everything out when each test finishes running. To that end, we want to override the tearDown() function on XCTestCase. Here we will simply set our Car to nil, eliminating any state they had.

override func tearDown() {
 ferrari = nil
 jeep = nil
 honda = nil

7. Write a real Unit test Swift

At this instant that we’ve set up a test case to pit our Car against each other, we want to write a test that demonstrates how a sports car does faster than a jeep car.

func testSportFasterThanJeep() {
 let minutes = 60
 //1 start ferrari
 ferrari.start(minutes: minutes)
 //2 start jeep
 jeep.start(minutes: minutes)
 //Test it
 XCTAssertTrue(ferrari.miles > jeep.miles)

Try it out by running this

That final line of code you notice is an assertion. It is a pass/fail sort of test. If the assertion passes, your test will pass. If the assertion fails, your test will fail.

Want to create an iPhone app that generates results? Click here to get started.






Leave a Reply

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