Writing Unit Tests for iOS Apps (XCTest)
Imagine a ViewModel that has grown to 700 lines—business logic mixed with data formatting and direct network calls. You add a new feature, and an old flow breaks. You roll back, it works again, but the cause is unclear. That's exactly when we write unit tests with XCTest. Our approach is not to chase 100% coverage, but to enable refactoring without fear. We test only what can break: business logic, edge cases, asynchronous operations. Over years of work on iOS projects, we have implemented unit tests in more than 30 projects for clients across industries—from fintech to e-commerce. We ensure stability in CI and provide transparent coverage reports. In this article, we'll explain exactly how we do it and why XCTest is the best choice for iOS.
Which Unit Tests to Write First?
Business logic is the top priority. ViewModel, Interactor, UseCase—anything with if/switch branches, calculations, data transformations. Swift's protocol-oriented approach makes this convenient: dependencies are injected through protocols, and mocked in tests.
// 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) } How XCTest Helps with Asynchronous Code?
Modern Swift with async/await is tested natively: XCTest supports async test functions from iOS 15+ and Xcode 13+. For Combine-based code, we use XCTestExpectation + sink. We employ both approaches depending on architecture. In one project, we replaced 40% of slow integration tests with unit tests using mocks, cutting test run time from 20 minutes to 3.
// Combine: testing a 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) } Edge cases are what actually break in production: empty arrays, nil values, strings with Unicode, dates in different time zones. We test not just the happy path but exactly those edge cases.
Testing-Friendly Architecture
XCTest tests are easy to write when the architecture uses dependency inversion. MVVM with DI via initializer, Clean Architecture with UseCases—testable directly. Singletons and static methods are not. If a project does not use DI, part of the work is refactoring before writing tests.
A common problem: a ViewModel accesses UserDefaults directly or calls Date() directly. Both must be wrapped in protocols and injected—otherwise tests depend on system state and time of execution.
For example, in a food delivery project, we rewrote the ViewModel to MVVM with DI. After that, test coverage reached 85%, and regression time was cut in half.
Typical Mistakes in iOS Unit Tests
- Using
@testable importwithout-enable-testingflag in build settings—import doesn't work in CI. - Tests that depend on order—XCTest does not guarantee execution order; each test must be isolated via
setUp()/tearDown(). - Real network requests in tests—makes tests flaky and slow. Always mock via
URLProtocolsubclass or customURLSessionConfiguration.
Comparison of Test Types
| Test Type | What It Checks | Speed | Stability |
|---|---|---|---|
| Unit (XCTest) | Business logic, methods | Seconds | 100% |
| Integration | Module interactions | Minutes | Depends on environment |
| UI (XCUITest) | User scenarios | Minutes | 80-90% |
Unit tests with XCTest offer the best speed-to-reliability ratio. Our projects achieve 80% business logic coverage, reducing regression testing time by 40%. Unit tests on XCTest are 5 times faster than integration tests for checking business logic.
Table of Typical Problems and Solutions
| Problem | Consequence | Solution |
|---|---|---|
| No dependency inversion | Cannot substitute service | Inject via protocols |
| Using singletons | Tests not isolated | Replace with DI provider |
| Tests depend on time | Flaky results | Inject Date() through a protocol |
What Is Included
- Audit of existing code and architecture
- Identifying components for testing (minimal refactoring for DI)
- Writing unit tests with XCTest, mocks, and stubs
- Integrating into CI (GitHub Actions, Bitrise, GitLab CI)
- Coverage report (Xcode Coverage Report, xcov)
- Recommendations for test maintenance
Process
Audit existing code → Identify testable components → Minimal refactoring for DI if needed → Write tests → Integrate into CI → Provide coverage report.
Timeline: 3–5 days depending on codebase size and current level of architectural isolation.
We have been developing iOS apps for over 5 years and have implemented unit tests in 30+ projects. Order unit test implementation—and your code will become more reliable.







