Unit Test Development for iOS Application (XCTest)
Typical situation: ViewModel grows to 500 lines, mixes business logic, data formatting and direct network calls. Add new feature — something breaks in old flow. Revert — works again, but reason unclear. Unit tests on XCTest — not about "coverage for coverage," but about ability to refactor fearlessly.
What to Test and How
Business logic — main priority. ViewModel, Interactor, UseCase — everything with if/switch branches, calculations, data transformations. Protocol-oriented approach Swift makes this convenient: dependencies injected via protocols, in tests substituted with mocks.
// Service protocol
protocol UserServiceProtocol {
func fetchUser(id: String) async throws -> User
}
// Mock for tests
class MockUserService: UserServiceProtocol {
var stubbedUser: User?
var stubbedError: Error?
func fetchUser(id: String) async throws -> User {
if let error = stubbedError { throw error }
return stubbedUser!
}
}
// Test
func testFetchUserSuccess() async throws {
let mockService = MockUserService()
mockService.stubbedUser = User(id: "1", name: "Test")
let sut = UserViewModel(service: mockService)
await sut.loadUser(id: "1")
XCTAssertEqual(sut.user?.name, "Test")
XCTAssertFalse(sut.isLoading)
}
Asynchronous code — second by importance. Modern Swift with async/await tests natively: XCTest supports async test functions with iOS 15+ and Xcode 13+. For Combine-based code — XCTestExpectation + sink.
Edge cases — what really crashes in production: empty array, nil value, string with Unicode, date in different timezone. Not "happy path," but exact edge cases.
Architecture Convenient for Testing
XCTest tests write simply when architecture assumes dependency inversion. MVVM with DI through initializer, Clean Architecture with UseCase — test directly. Singletons and static methods — no. If project doesn't use DI, part of work — refactoring before writing tests.
Common problem: ViewModel calls UserDefaults directly, Date() directly. Both need wrapping in protocols and injecting — otherwise tests depend on system state and startup time.
Testing Combine and async/await
// Combine: test Publisher
func testPublisherEmitsValue() {
let expectation = expectation(description: "Value received")
var cancellables = Set<AnyCancellable>()
sut.statePublisher
.dropFirst() // skip initial state
.sink { state in
XCTAssertEqual(state, .loaded)
expectation.fulfill()
}
.store(in: &cancellables)
sut.loadData()
waitForExpectations(timeout: 2)
}
CI Integration
Run tests on each PR via xcodebuild test -scheme MyApp -destination 'platform=iOS Simulator,name=iPhone 15'. Matrix of iOS versions fixed in GitHub Actions / Bitrise configuration. Code coverage report via Xcode Coverage Report or xcov gem. Coverage goal — not 100%, but logic: ViewModel/Interactor/UseCase should be 80%+ covered, UI — don't touch with unit tests.
Typical iOS Unit Test Errors
-
@testable importwithout-enable-testingflag in build settings — import doesn't work in CI -
Tests dependent on order —
XCTestdoesn't guarantee execution order, each test isolated viasetUp()/tearDown() -
Real network requests in tests — test becomes unstable and slow. Always mock via
URLProtocolsubclass orURLSessionwith customURLSessionConfiguration
Process of Work
Code audit → isolate testable components → if needed minimal refactoring for DI → write tests → CI integration. Coverage report after completion.
Timeframe: 3–5 days depending on codebase volume and current level of architectural component isolation.







