top of page

Unit testing in Swift for iOS app development


Unit testing in Swift for iOS app development

Unit Testing is an essential aspect of any software development process, including iOS app development. It ensures that the app functions as expected and meets the requirements set out in the specification. Unit testing involves testing individual components or units of the app's code in isolation to verify their functionality.


In this blog, we will discuss how to perform unit testing in Swift for iOS app development.


Why Unit Testing?


Unit testing is essential for several reasons:

  1. Verification: It ensures that the code functions as expected and meets the requirements set out in the specification.

  2. Code quality: Unit testing helps developers to write better code by identifying and fixing errors early in the development process.

  3. Refactoring: It enables developers to make changes to the code without fear of breaking existing functionality.

  4. Debugging: Unit tests help to identify issues with the code, making it easier to debug.

Setting up Unit Testing in Xcode


Xcode provides built-in support for unit testing in Swift. To set up unit testing in Xcode, follow these steps:

  1. Create a new Xcode project by selecting File > New > Project.

  2. Select the iOS > Application > Single View App template, and click Next.

  3. Give your project a name, select a team, and choose a location to save it.

  4. Ensure that the "Include Unit Tests" checkbox is selected, and click Next.

  5. Choose a location to save the test target files and click Create.

Writing Unit Tests


Now that we have set up unit testing in Xcode let's write some unit tests. In this example, we will create a simple function that calculates the sum of two integers and write unit tests to verify its functionality.

  1. Open the project in Xcode and navigate to the Test Navigator by selecting View > Navigators > Show Test Navigator.

  2. Click the + button in the bottom left corner of the Test Navigator to create a new test case.

  3. Give your test case a name, select the target to test, and click Create.

  4. Xcode will generate a new test class that inherits from XCTestCase.

  5. Add the following code to the test class:

func testAddition() {
    let sum = add(2, 3)
    XCTAssertEqual(sum, 5, "Sum should be 5")
}

func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}

In the code above, we have created a function called add that calculates the sum of two integers. We have also written a test case called testAddition that calls the add function and verifies that the result is correct using the XCTAssertEqual function.


The XCTAssertEqual function compares the actual result with the expected result and generates an error message if they are not equal. In this case, the error message would be "Sum should be 5" if the sum is not equal to 5.


Writing Unit Tests for a Sample iOS App


Let's say we're building an app that allows users to track their daily water intake. We have a ViewController that displays a label showing the user's current water intake for the day. We want to write a unit test to make sure the label displays the correct value based on the user's input.


Here are the steps to create a unit test for this ViewController:

  1. Open your project in Xcode and navigate to the ViewController file you want to test.

  2. Create a new Swift file in your project (File > New > File) and choose "Unit Test Case Class" as the file type. Name the file something like "WaterTrackerTests".

  3. In the new file, import the module containing the ViewController you want to test. For example, if your ViewController is in a module named "WaterTracker", you would add the following line to the top of your file:

@testable import WaterTracker


Create a new test method in your test file that tests the functionality of your ViewController. For example:

func testWaterIntakeLabel() {
    let vc = ViewController()
    vc.waterIntake = 16
    vc.loadViewIfNeeded()
    XCTAssertEqual(vc.waterIntakeLabel.text, "16 oz")
}

This test creates an instance of the ViewController, sets the water intake to 16, loads the view, and then asserts that the text of the water intake label is "16 oz". This test checks that the label displays the correct value based on the user's input.


Running Unit Tests


Now that we have written a unit test let's run it to verify that it works correctly.

  1. Navigate to the Test Navigator and select the test case you just created.

  2. Click the Run button in the top left corner of the Xcode window to run the test.

  3. Xcode will display the test results in the Test Navigator, and the test case should have passed.


Tips for Writing Effective Unit Tests


Here are a few tips to keep in mind when writing unit tests for your iOS app:

  • Write tests early and often. It's much easier to fix errors early in the development process, so make sure to write tests for your code as you go.

  • Write tests for edge cases. Make sure to test your code in scenarios where unexpected input is provided, or the code is being used in an unexpected way.

  • Keep tests small and focused. Each test should only test one specific piece of functionality.

  • Use descriptive test names. This makes it easier to understand what the test is checking and what should happen if the test fails.

  • Make sure your tests are independent. Tests should not rely on each other or on external factors, such as network connectivity.

Conclusion


Unit testing is an essential aspect of iOS app development that helps to ensure that the app functions as expected and meets the requirements set out in the specification. In this blog, we have discussed how to set up unit testing in Xcode and how to write and run unit tests in Swift. We have also provided an example of how to write a unit test for a simple function that calculates the sum of two integers.

Blog for Mobile App Developers, Testers and App Owners

 

This blog is from Finotes Team. Finotes is a lightweight mobile APM and bug detection tool for iOS and Android apps.

In this blog we talk about iOS and Android app development technologies, languages and frameworks like Java, Kotlin, Swift, Objective-C, Dart and Flutter that are used to build mobile apps. Read articles from Finotes team about good programming and software engineering practices, testing and QA practices, performance issues and bugs, concepts and techniques. 

bottom of page