← 返回
未分类 中文

Swift Xctest

Swift 6 + XCTest testing patterns for macOS/iOS apps using SwiftData, EventKit, and SwiftUI
Swift 6 + XCTest 测试模式:macOS/iOS 应用(使用 SwiftData、EventKit 和 SwiftUI)
soponcd soponcd 来源
未分类 clawhub v1.0.0 1 版本 100000 Key: 无需
★ 0
Stars
📥 388
下载
💾 3
安装
1
版本
#latest

概述

Swift/XCTest Testing Skill

Expert-level XCTest patterns for Swift 6 macOS/iOS applications. Specialized for SwiftData, EventKit, SwiftUI, and strict concurrency.

When to Use

Use this skill when:

  • Writing XCTest for Swift 6 applications
  • Testing SwiftData models with in-memory containers
  • Testing Swift 6 actors and @MainActor isolation
  • Testing EventKit integrations
  • Testing SwiftUI views and @Observable ViewModels
  • Writing performance tests for macOS apps

Core Principles

1. SwiftData Testing Pattern

import SwiftData
import XCTest

@MainActor
final class ModelTests: XCTestCase {
    var container: ModelContainer!
    var context: ModelContext!

    override func setUp() async throws {
        try await super.setUp()
        // Use in-memory config for isolated tests
        let config = ModelConfiguration(isStoredInMemoryOnly: true)
        container = try ModelContainer(for: YourModel.self, configurations: config)
        context = container.mainContext
    }

    override func tearDown() async throws {
        container = nil
        context = nil
        try await super.tearDown()
    }
}

2. Swift 6 Actor Testing

@MainActor
final class ServiceTests: XCTestCase {
    var service: YourActor!

    override func setUp() async throws {
        try await super.setUp()
        service = YourActor()
    }

    func testActorMethod() async throws {
        // Actor-isolated tests work naturally with async
        let result = try await service.method()
        XCTAssertEqual(result, expected)
    }
}

3. Given-When-Then Pattern

func testFeature() async throws {
    // Given: Set up initial state
    let task = service.createTask(title: "Test")

    // When: Perform action
    task.complete()

    // Then: Verify result
    XCTAssertTrue(task.isCompleted)
}

4. Test Organization

@MainActor
final class FeatureTests: XCTestCase {
    // MARK: - Properties
    // Test dependencies

    // MARK: - Setup & Teardown
    // setUp/tearDown methods

    // MARK: - Unit Tests
    // Isolated tests

    // MARK: - Integration Tests
    // Tests across components

    // MARK: - Edge Cases
    // Boundary and error conditions

    // MARK: - Performance Tests
    // Performance benchmarks
}

Testing Guidelines

SwiftData Models

  • Always use ModelConfiguration(isStoredInMemoryOnly: true)
  • Mark test classes with @MainActor
  • Use try context.save() after mutations
  • Verify state with FetchDescriptor and #Predicate

Actors & Concurrency

  • Test classes interacting with actors should be @MainActor
  • Use await for all actor methods
  • Test isolation boundaries with nonisolated tests where appropriate

SwiftData Services

  • Use in-memory mode: YourService(inMemory: true)
  • Test fetch, create, update, delete operations
  • Verify FetchDescriptor queries with predicates

EventKit Mocking

  • Mock EKEventStore for isolated testing
  • Test permission handling scenarios
  • Verify EKReminder to model mapping

SwiftUI Views

  • Use @Testable import to access internal types
  • Test @Observable ViewModel behavior
  • Test state transitions and side effects

Best Practices

  1. Isolation: Each test should be independent
  2. Async-Safety: Use async/await for all async operations
  3. MainActor: Mark SwiftData tests with @MainActor
  4. Performance: Use measure blocks for critical paths
  5. Readability: Use Given-When-Then comments
  6. Organization: Group tests with // MARK: sections

Performance Testing

func testPerformance() async throws {
    measure {
        // Code to measure
        _ = service.process(data: largeDataSet)
    }
}

Common Test Patterns

Batch Query Testing

func testBatchFetchEfficiency() async throws {
    let ids = (0..<100).map { "ID-\($0)" }
    let start = Date()
    let results = service.fetch(by: ids)
    let duration = Date().timeIntervalSince(start)

    XCTAssertEqual(results.count, 100)
    XCTAssertLessThan(duration, 0.5, "Batch fetch should be fast")
}

Predicate Testing

func testPredicateFiltering() async throws {
    let descriptor = FetchDescriptor<IdentityMap>(
        predicate: #Predicate { $0.isDirty == true }
    )
    let results = try context.fetch(descriptor)
    XCTAssertEqual(results.count, expectedCount)
}

Running Tests

# Run all tests
xcodebuild test -scheme YourApp -destination 'platform=macOS'

# Run specific test
xcodebuild test -scheme YourApp -destination 'platform=macOS' \
  -only-testing:'YourAppTests/FeatureTests/testMethod'

# Run with performance output
xcodebuild test -scheme YourApp -destination 'platform=macOS' \
  -resultBundlePath ~/TestResults.xcresult

版本历史

共 1 个版本

  • v1.0.0 当前
    2026-03-31 10:40 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

design-media

Web Design Guidelines

soponcd
审查 UI 代码以确保符合 Web 界面规范,适用于“审查我的 UI”“检查可访问性”“审计设计”“审查 UX”“检查我的网站”等请求。
★ 3 📥 1,321
dev-programming

Mcporter

steipete
使用 mcporter CLI 直接列出、配置、认证及调用 MCP 服务器/工具(支持 HTTP 或 stdio),涵盖临时服务器、配置编辑及 CLI/类型生成功能。
★ 195 📥 67,525
dev-programming

Github

steipete
使用 `gh` CLI 与 GitHub 交互,通过 `gh issue`、`gh pr`、`gh run` 和 `gh api` 管理议题、PR、CI 运行及高级查询。
★ 677 📥 326,681