Swift MVVM with Combine and XCTest in UIKit
UIKit view models that XCTest drives synchronously: one Equatable state publisher, inputs as methods, injected services and an injected Combine scheduler.
On this page
My UIKit view models don't import UIKit. Each one is a plain class that publishes a single state value, takes inputs as method calls and receives its dependencies, scheduler included, through init. The view controller subscribes with sink and store(in:). With that shape, XCTest can call an input and assert the exact sequence of states on the next line, synchronously, with the network stubbed and no sleep anywhere.
I used this on the native iOS side of a banking app (UIKit screens, MVVM, Combine, XCTest on the view models). The example here is a generic screen that loads recent payments, and none of it comes from that codebase.
One state value out, method calls in
I model a screen as one state enum rather than several flags. Separate isLoading, error and items properties allow combinations that should never exist, like loading and failed at once. An Equatable enum makes them unrepresentable, and a test compares a single value.
The state is read-only from outside. @Published private(set) lets the view model write and everyone else read, and the AnyPublisher accessor hides how the state is produced.
Inputs are plain methods. A public PassthroughSubject would let any caller send a completion and silently kill the pipeline, which load() and retry() can't do.
Nothing from UIKit gets in: no UIImage, UIColor or IndexPath. The view model exposes values ready for display, and the view controller turns them into views.
import Combine
protocol PaymentsService {
func recentPayments() -> AnyPublisher<[Payment], Error>
}
enum PaymentsState: Equatable {
case idle, loading, loaded([Payment]), failed
}
@MainActor
final class PaymentsViewModel<S: Scheduler> {
@Published private(set) var state: PaymentsState = .idle
var statePublisher: AnyPublisher<PaymentsState, Never> { $state.eraseToAnyPublisher() }
private let reloads = PassthroughSubject<Void, Never>()
init(service: any PaymentsService, scheduler: S) {
reloads
.map { _ in
service.recentPayments()
.map(PaymentsState.loaded)
// Caught inside: a failure ends this request, not the pipeline.
.catch { _ in Just(PaymentsState.failed) }
.prepend(.loading)
}
.switchToLatest()
.receive(on: scheduler)
.assign(to: &$state)
}
func load() { reloads.send() }
func retry() { reloads.send() }
}Where catch sits matters. It's inside the inner publisher, so an error ends one request and the stream keeps running. Put it after switchToLatest and the first failure completes the pipeline, after which retry() does nothing. switchToLatest also drops an in-flight request when a new reload arrives, so a double tap never shows stale results.
Inject services through init, behind a protocol
The view model talks to PaymentsService, never to URLSession, a decoder or an API client. The live implementation wraps the networking layer; tests pass a stub.
I inject through init rather than through properties or a shared singleton. The dependencies are visible in the signature, and the object can't exist half-configured. The coordinator builds PaymentsViewModel(service: LivePaymentsService(client: apiClient), scheduler: DispatchQueue.main) and hands it to the view controller.
I don't put a protocol in front of everything, though. Formatters and mappers are deterministic, so I test them directly. Protocols pay off around side effects and non-determinism: network, storage, time and threads.
The scheduler is a dependency too
Hardcode receive(on: DispatchQueue.main) and every state change becomes asynchronous, even when you're already on the main thread, because a dispatch queue always enqueues the work. Each test then needs an expectation and a timeout, and an assertion placed right after an input is quietly wrong.
Making the view model generic over S: Scheduler fixes that. Production passes DispatchQueue.main. Tests pass ImmediateScheduler.shared, which ships with Combine and runs the work synchronously, so calling load() and asserting on the next line is correct.
The same scheduler drives time-based operators. A debounced search would use debounce(for: .milliseconds(300), scheduler: scheduler), and with ImmediateScheduler it fires at once. That's fine for state tests and no help for checking the timing itself. For that, use a virtual-time scheduler you advance by hand, such as the TestScheduler in Point-Free's combine-schedulers.
The cost is the generic parameter, which leaks into the view controller's property type. For a few screens I accept it. Once it spreads, a type-erased scheduler keeps signatures clean (combine-schedulers ships AnySchedulerOf<DispatchQueue>). The view model is also @MainActor, because its state is UI state and the compiler should know that.
The view controller renders state and forwards events
import Combine
import UIKit
final class PaymentsViewController: UIViewController {
private let viewModel: PaymentsViewModel<DispatchQueue>
private var cancellables = Set<AnyCancellable>()
private let spinner = UIActivityIndicatorView(style: .medium)
init(viewModel: PaymentsViewModel<DispatchQueue>) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
override func viewDidLoad() {
super.viewDidLoad()
viewModel.statePublisher
.sink { [weak self] state in self?.render(state) }
.store(in: &cancellables)
viewModel.load()
}
private func render(_ state: PaymentsState) {
if state == .loading { spinner.startAnimating() } else { spinner.stopAnimating() }
switch state {
case .idle, .loading: break
case .loaded(let payments): applySnapshot(payments) // diffable data source
case .failed: showRetry { [weak self] in self?.viewModel.retry() }
}
}
}This is the only place UIKit appears. render takes the whole state and redraws from it, so there's no event-specific branching to keep in sync, and for lists a diffable data source keeps that cheap.
There's no receive(on:) here. The view model already guarantees delivery on the main thread, and threading needs only one owner.
Subscriptions live in cancellables, which goes away with the view controller and cancels them. Never write _ = publisher.sink { ... }: the discarded AnyCancellable cancels the subscription on the spot.
Retain cycles hide in sink and assign(to:on:)
The usual cycle: the view controller owns cancellables, which owns the subscription, which owns the sink closure, which captures the view controller. [weak self] breaks it. The same applies to any closure a view stores, like the retry action above.
assign(to: \.state, on: self) is the less obvious one. It keeps a strong reference to self, so storing that cancellable on self gives you a cycle. assign(to: &$state) ties the subscription to the property's lifetime instead. The view model's own pipeline captures service and never self, so there's nothing to weaken there.
I avoid [unowned self] in Combine code: a value that arrives after deallocation turns a leak into a crash. And rather than trust review to spot cycles, I let a test catch them.
Collect every emitted state, then assert the sequence
import Combine
import XCTest
@testable import MyApp
final class PaymentsServiceStub: PaymentsService {
var result: Result<[Payment], Error>
init(_ result: Result<[Payment], Error>) { self.result = result }
func recentPayments() -> AnyPublisher<[Payment], Error> { result.publisher.eraseToAnyPublisher() }
}
final class PaymentsViewModelTests: XCTestCase {
@MainActor func test_load_emitsLoadingThenLoaded() {
let sut = makeSUT(PaymentsServiceStub(.success([.fixture()])))
var states: [PaymentsState] = []
let subscription = sut.statePublisher.sink { states.append($0) }
sut.load()
XCTAssertEqual(states, [.idle, .loading, .loaded([.fixture()])])
subscription.cancel()
}
@MainActor func test_retry_afterFailure_loadsAgain() {
let service = PaymentsServiceStub(.failure(URLError(.notConnectedToInternet)))
let sut = makeSUT(service)
sut.load()
XCTAssertEqual(sut.state, .failed)
service.result = .success([.fixture()])
sut.retry()
XCTAssertEqual(sut.state, .loaded([.fixture()]))
}
@MainActor private func makeSUT(_ service: PaymentsServiceStub) -> PaymentsViewModel<ImmediateScheduler> {
let sut = PaymentsViewModel(service: service, scheduler: ImmediateScheduler.shared)
addTeardownBlock { [weak sut] in XCTAssertNil(sut, "PaymentsViewModel leaked") }
return sut
}
}Collecting every state checks the order as well as the final value: drop the .loading state or emit twice, and the first test fails. The retry test pins down the catch placement, the regression I'd least like to find in production. The teardown block in makeSUT fails any test that leaves the view model alive, which is how retain cycles get caught in CI instead of in Instruments. Test methods are @MainActor because the view model is.
For a test of the wiring itself, on the real main queue, I use an expectation and the async fulfillment(of:timeout:):
@MainActor func test_load_onMainQueue_deliversLoadedLater() async {
let sut = PaymentsViewModel(service: PaymentsServiceStub(.success([])),
scheduler: DispatchQueue.main)
let loaded = expectation(description: "reaches .loaded")
let subscription = sut.statePublisher.sink { state in
if state == .loaded([]) { loaded.fulfill() }
}
sut.load()
XCTAssertEqual(sut.state, .idle) // nothing has reached the main queue yet
await fulfillment(of: [loaded], timeout: 1)
subscription.cancel()
}The .idle assertion documents the trap from the scheduler section. I keep these tests few, since each one waits on the run loop and the immediate scheduler already covers the logic.
What changes with SwiftUI and @Observable
For SwiftUI screens on iOS 17 and later, I write this differently. An @Observable class exposes plain stored properties and SwiftUI tracks what each view reads, so @Published, publishers and cancellables disappear from the view layer. Inputs become async methods, and the test reads like a specification: await sut.load(), then XCTAssertEqual(sut.state, .loaded(payments)), with no scheduler and no expectation. For time-based logic, inject a Clock instead of a scheduler. Recent UIKit versions can also observe @Observable models in update methods such as layoutSubviews; check that against your deployment target before relying on it.
Combine is still the better fit when the problem really is a stream: search-as-you-type with debounce, merging several sources, a socket feed. It's also the pragmatic choice in an existing UIKit codebase built around it.