Unit testing with XCTest and mocks

4444
0

Unit tests verify code behavior in isolation using XCTest framework. I create test classes inheriting from XCTestCase with test prefixed methods. Each test has arrange-act-assert structure: set up dependencies, execute code, verify results with XCTAssert methods. For testing ViewModels, I inject mock dependencies through initializers to control external behavior. Mocks implement protocols, returning predetermined values or tracking method calls. Async tests use expectations—create with expectation(description:), fulfill when async completes, wait with waitForExpectations. Test-driven development guides design toward testable, decoupled code. Running tests frequently catches regressions early.