Unit test Cases with Swift

10 Reasons to Write Unit Tests

Its Reduce Bugs in New Features.

Its Reduce Bugs in Existing Features.

Its Reduce the Cost of Change.

Improve Design.

Permit Refactoring.

Constrain Features.

Defend Against Other Programmers.

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 to include 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.

  • 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 yours methods public.

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 which 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() {
 super.viewDidLoad()
 let ferrari = Car(type: .Sport, transmissionMode: .Drive)
 ferrari.start(minutes: 120)
 print(ferrari.miles) // => 140
 }
 override func didReceiveMemoryWarning() {
 super.didReceiveMemoryWarning()
 }
}

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

5 Creating a Car Unit Test Case

To create 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

When 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() {
 super.setUp()
 }
 override func tearDown() {
 super.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 optionals (!) 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, 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() {
 super.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() {
 super.tearDown()
 ferrari = nil
 jeep = nil
 honda = nil
}

7 Write a real test

At this instant that we’ve setup a test case to pit our Car against each other, we want to write a test that demonstrates how a sport car does more fast to 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.

Last Update: September 26, 2018  

September 26, 2018   120   Nandini R    Swift Significance    
Total 0 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

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

Facebook
Twitter
INSTAGRAM
LinkedIn