Omer Cagri Sayir
HomeAboutBlogBookmarks
Sign In
HomeAboutBlogBookmarks
Sign In

Made with ❤️ by Omer - 2025

GitHubTwitterLinkedIn
Testing Swift

Testing Swift

By Omer Cagri Sayir•4 months ago

Table of Contents

  • Why test?
  • Commands
  • Details
  • Lifecycle
  • Example Unit Test

Why test?

To develop the app better. Also, it helps to understand our expectations.

Commands

CMD + U --> Starts the test in XCode

Details

import XCTest --> Imports the framework

By default, all types and their properties have an "internal" protection level. @testable attribute automatically gives your tests the same access to code.

Private code is supposed to be private, and so it should NOT be tested.

Lifecycle

class func setup() -> setup() -> testFunc1() -> teardown() -> setup() -> testFunc2() -> teardown -> class func teardown()

Example Unit Test

struct Converter { func converToCelsius(fahrenfeit: Double) -> Double { return (fahrenheit - 32) * 5 / 9 } }
func testFahrenheitToCelsius() { let sut = Converter() let input1 = 30.0 let output1 = sut.convertToCelsius(fahrenheit: input1) XCTAssertEqual(output1, 0) let input2 = 210.0 let output2 = sut.convertToCelsius(fahrenheit: input2) XCTAssertEqual(output2, 100) }

Note: sut is special for unit tests. It's short for "system under test" and its used to refer whatever object you are testing in the code.