Write unit tests with XCTest and UI tests with XCUITest.
Testing Overview
# Frameworks: XCTest (unit), XCUITest (UI)
# Target: Add Unit Test Target, UI Test Target
# Run: Cmd+U (test), Cmd+Option+Cmd+U (test with coverage)Unit Tests with XCTest
import XCTest
@testable import MyApp
// Test case
final class UserViewModelTests: XCTestCase {
var viewModel: UserViewModel!
var mockService: MockUserService!
override func setUp() {
super.setUp()
mockService = MockUserService()
viewModel = UserViewModel(userService: mockService)
}
override func tearDown() {
viewModel = nil
mockService = nil
super.tearDown()
}
// Async test
func testLoadUsersSuccess() async throws {
// Given
let expectedUsers = [
User(id: "1", name: "John", email: "john@example.com"),
User(id: "2", name: "Jane", email: "jane@example.com")
]
mockService.users = expectedUsers
// When
await viewModel.loadUsers()
// Then
XCTAssertEqual(viewModel.users.count, 2)
XCTAssertEqual(viewModel.users[0].name, "John")
XCTAssertNil(viewModel.error)
XCTAssertFalse(viewModel.isLoading)
}
func testLoadUsersFailure() async throws {
// Given
mockService.shouldThrow = true
// When
await viewModel.loadUsers()
// Then
XCTAssertTrue(viewModel.users.isEmpty)
XCTAssertNotNil(viewModel.error)
XCTAssertFalse(viewModel.isLoading)
}
func testDeleteUser() async throws {
// Given
let user = User(id: "1", name: "John", email: "john@example.com")
mockService.users = [user]
await viewModel.loadUsers()
// When
await viewModel.deleteUser(user)
// Then
XCTAssertTrue(viewModel.users.isEmpty)
XCTAssertTrue(mockService.deleteCalled)
}
// Test with expectations (for callbacks/combine)
func testPublisher() {
let expectation = XCTestExpectation(description: "Publisher emits")
viewModel.$users
.dropFirst()
.sink { users in
XCTAssertEqual(users.count, 1)
expectation.fulfill()
}
.store(in: &cancellables)
Task { await viewModel.loadUsers() }
wait(for: [expectation], timeout: 2.0)
}
// Performance test
func testPerformance() {
measure {
// Code to measure
for _ in 0..<1000 {
_ = User(id: UUID().uuidString, name: "Test", email: "test@test.com")
}
}
}
private var cancellables = Set<AnyCancellable>()
}Mocking
// Protocol for testability
protocol UserServiceProtocol {
func fetchUsers() async throws -> [User]
func deleteUser(_ id: String) async throws
}
// Mock implementation
class MockUserService: UserServiceProtocol {
var users: [User] = []
var shouldThrow = false
var deleteCalled = false
var deletedId: String?
func fetchUsers() async throws -> [User] {
if shouldThrow { throw URLError(.badServerResponse) }
return users
}
func deleteUser(_ id: String) async throws {
deleteCalled = true
deletedId = id
if shouldThrow { throw URLError(.badServerResponse) }
users.removeAll { $0.id == id }
}
}
// Protocol-based DI for testing
class UserViewModel: ObservableObject {
@Published var users: [User] = []
@Published var isLoading = false
@Published var error: String?
private let userService: UserServiceProtocol
init(userService: UserServiceProtocol = UserService()) {
self.userService = userService
}
@MainActor
func loadUsers() async {
isLoading = true
error = nil
do {
users = try await userService.fetchUsers()
} catch {
self.error = error.localizedDescription
}
isLoading = false
}
@MainActor
func deleteUser(_ user: User) async {
do {
try await userService.deleteUser(user.id)
users.removeAll { $0.id == user.id }
} catch {
self.error = error.localizedDescription
}
}
}Testing Async Code
// Testing async/await
func testAsyncFunction() async throws {
let result = try await someAsyncFunction()
XCTAssertEqual(result, expected)
}
// Testing async with timeout
func testAsyncTimeout() async throws {
let expectation = XCTestExpectation(description: "Async completes")
Task {
await someAsyncFunction()
expectation.fulfill()
}
await fulfillment(of: [expectation], timeout: 5.0)
}
// Testing concurrent operations
func testConcurrentRequests() async throws {
async let result1 = fetchData(id: 1)
async let result2 = fetchData(id: 2)
async let result3 = fetchData(id: 3)
let (r1, r2, r3) = try await (result1, result2, result3)
XCTAssertNotNil(r1)
XCTAssertNotNil(r2)
XCTAssertNotNil(r3)
}Testing SwiftUI Views
import XCTest
import SwiftUI
@testable import MyApp
// Snapshot testing (requires snapshot testing library)
class ViewTests: XCTestCase {
func testCounterView() {
let view = CounterView()
let hostingController = UIHostingController(rootView: view)
// Test initial state
XCTAssertEqual(view.count, 0)
// Simulate tap
view.increment()
XCTAssertEqual(view.count, 1)
}
}
// Testing with ViewInspector (third party)
// import ViewInspector
// func testButtonTap() throws {
// let view = CounterView()
// let button = try view.inspect().find(button: "Increment")
// try button.tap()
// XCTAssertEqual(try view.inspect().find(text: "1").string(), "1")
// }UI Tests with XCUITest
import XCTest
final class MyAppUITests: XCTestCase {
let app = XCUIApplication()
override func setUp() {
super.setUp()
continueAfterFailure = false
app.launchArguments = ["-UITest", "true"]
app.launch()
}
override func tearDown() {
app.terminate()
super.tearDown()
}
func testLoginFlow() {
// Given: on login screen
let emailField = app.textFields["emailField"]
let passwordField = app.secureTextFields["passwordField"]
let loginButton = app.buttons["loginButton"]
XCTAssertTrue(emailField.waitForExistence(timeout: 5))
// When: enter credentials and tap login
emailField.tap()
emailField.typeText("test@example.com")
passwordField.tap()
passwordField.typeText("password123")
loginButton.tap()
// Then: should navigate to home
let homeTitle = app.staticTexts["Home"]
XCTAssertTrue(homeTitle.waitForExistence(timeout: 5))
}
func testAddTodo() {
// Navigate to todo list
app.tabBars.buttons["Todos"].tap()
// Tap add button
app.buttons["Add Todo"].tap()
// Enter todo
let textField = app.textFields["todoTextField"]
XCTAssertTrue(textField.waitForExistence(timeout: 3))
textField.tap()
textField.typeText("New todo item")
// Save
app.buttons["Save"].tap()
// Verify in list
let todoItem = app.staticTexts["New todo item"]
XCTAssertTrue(todoItem.waitForExistence(timeout: 3))
}
func testSwipeToDelete() {
app.tabBars.buttons["Todos"].tap()
// Swipe to delete
let cell = app.cells["todo_0"]
cell.swipeLeft()
app.buttons["Delete"].tap()
// Verify removed
XCTAssertFalse(cell.waitForExistence(timeout: 2))
}
func testPullToRefresh() {
app.tabBars.buttons["Todos"].tap()
let list = app.collectionViews.firstMatch
let firstCell = list.cells.firstMatch
// Pull down
let start = firstCell.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))
let end = firstCell.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 2.0))
start.press(forDuration: 0.5, thenDragTo: end)
// Verify refresh indicator
let refreshIndicator = app.activityIndicators["refreshIndicator"]
XCTAssertTrue(refreshIndicator.waitForExistence(timeout: 3))
}
}
// Accessibility identifiers (add to SwiftUI views)
/*
TextField("Email", text: $email)
.accessibilityIdentifier("emailField")
Button("Login") { }
.accessibilityIdentifier("loginButton")
List {
ForEach(todos) { todo in
Text(todo.title)
.accessibilityIdentifier("todo_\(todo.id)")
}
}
*/Test Organization
// Test suite structure
final class MyAppTests: XCTestCase {
// MARK: - Unit Tests
func testModelEncoding() { }
func testViewModelLogic() { }
func testServiceLayer() { }
// MARK: - Integration Tests
func testNetworkLayer() { }
func testDatabaseLayer() { }
// MARK: - UI Tests (in separate target)
// MyAppUITests
}
// Shared test utilities
struct TestHelpers {
static func createMockUser(id: String = "1") -> User {
User(id: id, name: "Test User", email: "test@example.com")
}
static func waitForElement(_ element: XCUIElement, timeout: TimeInterval = 5) -> Bool {
element.waitForExistence(timeout: timeout)
}
}Code Coverage
# Enable in Scheme: Test → Options → Code Coverage
# Or: xcodebuild test -scheme MyApp -enableCodeCoverage YES
# View coverage in Xcode: Report Navigator → Coverage
# Export: xcrun xccov view --report --json build/Logs/Test/*.xcresult > coverage.json// Exclude from coverage
// swiftlint:disable:next no_direct_standard_out_log
@inline(__always) func notCovered() { }
// Or use @available to conditionally compile
#if DEBUG
// Test-only code
#endifContinuous Integration
# .github/workflows/test.yml
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- name: Select Xcode
run: sudo xcode-select -s /Applications/Xcode_15.2.app
- name: Run tests
run: |
xcodebuild test \
-workspace MyApp.xcworkspace \
-scheme MyApp \
-destination 'platform=iOS Simulator,name=iPhone 15 Pro,OS=17.2' \
-enableCodeCoverage YES \
-quiet
- name: Upload coverage
uses: codecov/codecov-action@v3
with:
files: ./coverage.xcresultTry It
Add Unit Test target. Write XCTest for ViewModel. Add UI Test target. Record UI test. Run with coverage. Set up GitHub Actions.
# Xcode → File → New → Target → Unit Test Target
# Xcode → File → New → Target → UI Test Target
# Cmd+U to run testsTesting mastery
- Set up Unit Test and UI Test targets
- Write unit tests for ViewModels with mocks
- Test async/await code with expectations
- Write XCUITest for critical user flows
- Add accessibility identifiers for testing
- Configure code coverage
- Set up GitHub Actions for CI
- Achieve 80%+ coverage
XCTest for unit tests, XCUITest for UI tests. Use protocols for mocking. Test async with async/await or expectations. UI tests use accessibility identifiers. Run in CI with xcodebuild. Target 80%+ coverage.