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.mdSao 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
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
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
Bình luận
- …
Thêm skill từ kho mã này
accessibility
280kGiúp agent của bạn tạo giao diện mà ai cũng dùng được, đảm bảo website và app hoạt động tốt với người khuyết tật như người mù hoặc khó vận động.
agent-architecture-audit
280kGiúp agent của bạn kiểm tra xem mọi thứ có hoạt động đúng không, đồng thời tìm và sửa các lỗi trong hệ thống AI để chúng chạy như mong đợi.
agent-eval
280kGiúp agent của bạn so sánh các công cụ lập trình AI khác nhau, đo xem công cụ nào nhanh hơn, rẻ hơn và đáng tin cậy hơn cho từng tác vụ.
agent-harness-construction
280kGiúp agent của bạn hiểu rõ hơn cách thực hiện tác vụ, tối ưu các công cụ và chỉ dẫn mà agent dùng để tăng khả năng thành công.
Skill tương tự
test-driven-development
311kDạy agent của bạn viết kiểm thử thất bại trước, xem nó thất bại, rồi viết đoạn mã ngắn nhất để vượt qua trước khi làm bất kỳ tính năng hay bản sửa nào.
verification-before-completion
311kDạy agent của bạn chạy kiểm tra thực tế và đọc kết quả đầu ra trước khi khẳng định một việc, bản sửa hoặc bản build đã hoàn thành hay vượt qua.
migrate-to-shoehorn
310kThay các ép kiểu rủi ro trong tệp kiểm thử bằng thư viện shoehorn, để các bài kiểm thử dùng dữ liệu một phần vẫn qua được kiểm tra kiểu.