- 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
- 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]
- Adding
@testable attribute to import statement provides elevated access setUp() is called before each tests are runtearDownWithError() 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 {
}
}
- 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)
}
}
- There are seeveral
XCTAsserts worth using, the xample below highlights a few of them:
func testNotableXCTAssert() {
let falseBoolResult = false
XCTAssertFalse(falseBoolResult)
let nilResult: String? = nil
XCTAssertNil(nilResult)
let greaterThanResult = 12
XCTAssertGreaterThanOrEqual(graterThanResult, 11)
let notEqualString = "Example"
XCTAssertNotEqual(notEqualString, "Test?")
}
- 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.