Swift Testing is the current framework and it is a pleasure next to XCTest: a test is a function marked @Test, an assertion is #expect, and a failure prints the actual values on both sides of the comparison without you formatting a message. XCTest still exists, still works, and is still what UI tests are written in, so you will read both.
Test the ViewModel, not the view. With the dependency injection from two topics ago, a test constructs the model with a stub, awaits a method, and checks the published state. It runs in milliseconds and never touches the network. A UI test drives the real app through the accessibility tree, which makes it slow and more brittle - reserve it for a handful of critical journeys like sign-in and purchase rather than trying to cover the app with it.
For problems that are not logic errors, Xcode ships Instruments. The Leaks and Allocations instruments find retain cycles - the classic one being a closure capturing self strongly, which [weak self] fixes. Time Profiler shows where the frames go. The Memory Graph Debugger, a button in the debug bar, is often quicker than any of them: pause the app, look at what is still alive that should not be.
import Testing
@testable import MyApp
// Swift Testing: a function, a tag, and #expect.
@Test("A successful fetch publishes the articles")
@MainActor
func loadsArticles() async {
let stub = StubArticleService(result: .success([
Article(id: 1, title: "First", publishedAt: .now, author: .init(name: "Ada")),
]))
let model = ArticleListModel(service: stub)
await model.load()
#expect(model.articles.count == 1)
#expect(model.articles.first?.title == "First")
#expect(model.failure == nil)
}
@Test("A failed fetch shows a message and keeps the list empty")
@MainActor
func showsFailure() async {
let stub = StubArticleService(result: .failure(URLError(.notConnectedToInternet)))
let model = ArticleListModel(service: stub)
await model.load()
#expect(model.articles.isEmpty)
#expect(model.failure != nil)
}
// The retain cycle Instruments will find if you forget [weak self].
final class Uploader {
var onFinish: (() -> Void)?
func start() {
onFinish = { [weak self] in
guard let self else { return }
self.cleanUp()
}
}
func cleanUp() { }
}