Chuyển đến nội dung
Skillpedia
Kiểm thử280k · #251

swift-protocol-di-testing

Skill này làm gì

Công cụ này giúp code Swift của bạn dễ test hơn. Nó cho phép bạn tạo phiên bản 'giả' (mock) của các phần chương trình tương tác với thế giới bên ngoài, như hệ thống tệp hoặc internet, để test code mà không thực sự dùng đến chúng.

Khi nào nên dùng

  • ✓Khi viết code Swift để lưu hoặc đọc tệp.
  • ✓Khi cần test cách code phản ứng với lỗi mạng.
  • ✓Khi xây dựng các phần của ứng dụng cần hoạt động trong nhiều tình huống khác nhau, như ứng dụng chính và khi test.

Liên kết skill

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/swift-protocol-di-testing/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/swift-protocol-di-testing/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để test code lưu dữ liệu vào tệp mà không thực sự lưu tệp nào?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Bạn định nghĩa các 'quy tắc' nhỏ (protocol) cho các tương tác bên ngoài. Sau đó, bạn tạo phần triển khai thật để dùng bình thường và phần triển khai 'giả' cho test. Code của bạn dùng các quy tắc này, còn trong test bạn yêu cầu nó dùng phiên bản giả.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

Swift Protocol-Based Dependency Injection for Testing

Patterns for making Swift code testable by abstracting external dependencies (file system, network, iCloud) behind small, focused protocols. Enables deterministic tests without I/O.

When to Activate

  • Writing Swift code that accesses file system, network, or external APIs
  • Need to test error handling paths without triggering real failures
  • Building modules that work across environments (app, test, SwiftUI preview)
  • Designing testable architecture with Swift concurrency (actors, Sendable)

Core Pattern

1. Define Small, Focused Protocols

Each protocol handles exactly one external concern.

// File system access
public protocol FileSystemProviding: Sendable {
    func containerURL(for purpose: Purpose) -> URL?
}

// File read/write operations
public protocol FileAccessorProviding: Sendable {
    func read(from url: URL) throws -> Data
    func write(_ data: Data, to url: URL) throws
    func fileExists(at url: URL) -> Bool
}

// Bookmark storage (e.g., for sandboxed apps)
public protocol BookmarkStorageProviding: Sendable {
    func saveBookmark(_ data: Data, for key: String) throws
    func loadBookmark(for key: String) throws -> Data?
}

2. Create Default (Production) Implementations

public struct DefaultFileSystemProvider: FileSystemProviding {
    public init() {}

    public func containerURL(for purpose: Purpose) -> URL? {
        FileManager.default.url(forUbiquityContainerIdentifier: nil)
    }
}

public struct DefaultFileAccessor: FileAccessorProviding {
    public init() {}

    public func read(from url: URL) throws -> Data {
        try Data(contentsOf: url)
    }

    public func write(_ data: Data, to url: URL) throws {
        try data.write(to: url, options: .atomic)
    }

    public func fileExists(at url: URL) -> Bool {
        FileManager.default.fileExists(atPath: url.path)
    }
}

3. Create Mock Implementations for Testing

public final class MockFileAccessor: FileAccessorProviding, @unchecked Sendable {
    public var files: [URL: Data] = [:]
    public var readError: Error?
    public var writeError: Error?

    public init() {}

    public func read(from url: URL) throws -> Data {
        if let error = readError { throw error }
        guard let data = files[url] else {
            throw CocoaError(.fileReadNoSuchFile)
        }
        return data
    }

    public func write(_ data: Data, to url: URL) throws {
        if let error = writeError { throw error }
        files[url] = data
    }

    public func fileExists(at url: URL) -> Bool {
        files[url] != nil
    }
}

4. Inject Dependencies with Default Parameters

Production code uses defaults; tests inject mocks.

public actor SyncManager {
    private let fileSystem: FileSystemProviding
    private let fileAccessor: FileAccessorProviding

    public init(
        fileSystem: FileSystemProviding = DefaultFileSystemProvider(),
        fileAccessor: FileAccessorProviding = DefaultFileAccessor()
    ) {
        self.fileSystem = fileSystem
        self.fileAccessor = fileAccessor
    }

    public func sync() async throws {
        guard let containerURL = fileSystem.containerURL(for: .sync) else {
            throw SyncError.containerNotAvailable
        }
        let data = try fileAccessor.read(
            from: containerURL.appendingPathComponent("data.json")
        )
        // Process data...
    }
}

5. Write Tests with Swift Testing

import Testing

@Test("Sync manager handles missing container")
func testMissingContainer() async {
    let mockFileSystem = MockFileSystemProvider(containerURL: nil)
    let manager = SyncManager(fileSystem: mockFileSystem)

    await #expect(throws: SyncError.containerNotAvailable) {
        try await manager.sync()
    }
}

@Test("Sync manager reads data correctly")
func testReadData() async throws {
    let mockFileAccessor = MockFileAccessor()
    mockFileAccessor.files[testURL] = testData

    let manager = SyncManager(fileAccessor: mockFileAccessor)
    let result = try await manager.loadData()

    #expect(result == expectedData)
}

@Test("Sync manager handles read errors gracefully")
func testReadError() async {
    let mockFileAccessor = MockFileAccessor()
    mockFileAccessor.readError = CocoaError(.fileReadCorruptFile)

    let manager = SyncManager(fileAccessor: mockFileAccessor)

    await #expect(throws: SyncError.self) {

…
Câu hỏi thường gặp

'Protocol' trong ngữ cảnh này là gì?

Đây là các hợp đồng xác định code có thể làm gì, mà không nói rõ cách làm. Nhờ vậy có thể thay phần triển khai thật bằng phần giả khi test.

'Dependency injection' là gì?

Đó là việc cung cấp những phần mà code cần (như truy cập tệp) từ bên ngoài, thay vì tự code tạo ra. Điều này giúp dễ thay bằng phiên bản giả khi test.

Vì sao dùng 'mock'?

Mock là các phiên bản giả của phần code. Chúng cho phép mô phỏng những tình huống cụ thể (như lỗi hoặc dữ liệu nhất định) để test code một cách có kiểm soát và đáng tin cậy, không phụ thuộc vào môi trường thật.

Chi tiết

Mô tả gốc của tác giả

Protocol-based dependency injection for testable Swift code — mock file system, network, and external APIs using focused protocols and Swift Testing. Use when Swift code needs testing and file system, network, or external APIs must be mocked.

repo: affaan-m/ECC

Độ phổ biến

Sao GitHub
280k
Vị trí xếp hạng
#251
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự