Skip to main content

Unit Test

About 1 minSwiftiosswiftxctest

Unit Test 관련


Intro

  • Unit tests are means of testing small bits of code
  • This works well to reduce bugs in new and existing features
  • A unit test is essentially a function that invokes some code and asserts that certain conditions are satisfied during code execution

xctest

  • Xcode's testing framework for unit testing
  • Integerates seamlessly with Xcode's testing workflow
  • XCTests can be added when creating a new project or through [File] > [New] > [Target] > [Unit Testing Bundle]

xctest class

  • Adding @testable attribute to import statement provides elevated access
  • setUp() is called before each tests are run
  • tearDownWithError() provides an opportunity to perform cleanup and to throw errors after each test
import XCTest
@testable import BMI_Calculator

class PROJECTNAMETests: XCTestCase {
    override func setUpWithError() throws {
        
    }
    override func tearDownWithError() throws {
        
    }
}

Example

  • Test should be written as functions, the below struct calculates a user BMI - function need to be named as test..()
struct BMICalculator {
    var weightKG: Int
    var heightM: Double
    func returnBMI() -> Double {
        return Double(weightKG) / (heightM * heightM)
    }
}

class BMI_CalculatorTests: XCTestCase {
    func testBMI() {
        let bmiTest = BMICalculator(weightKG: 68, heightM: 1.77)
        let result = bmiTest.returnBMI()
        XCTAssertEqual(result, 21.70512943279896)
    }
}

Notable XCTAssert

  • There are seeveral XCTAsserts worth using, the xample below highlights a few of them:
func testNotableXCTAssert() {
    // Bool
    let falseBoolResult = false
    XCTAssertFalse(falseBoolResult)

    // Nil
    let nilResult: String? = nil
    XCTAssertNil(nilResult)

    // Greater Than / Less Than
    let greaterThanResult = 12
    XCTAssertGreaterThanOrEqual(graterThanResult, 11)

    // Strings
    let notEqualString = "Example"
    XCTAssertNotEqual(notEqualString, "Test?")
}

Summary

  • Testing reduces bugs - especially on larger project with several developers
  • Unit tests CAN be skipped or disabled
  • All unit tests are functions that MUST include "test" in the function name
  • Keep tests simple so that you're only testing a unit.
이찬희 (MarkiiimarK)
Never Stop Learning.