본문으로 건너뛰기
Skillpedia
테스트280k · #251

swift-protocol-di-testing

하는 일

이 도구는 Swift 코드를 더 쉽게 테스트하도록 돕습니다. 파일 시스템이나 인터넷처럼 외부와 상호작용하는 프로그램의 부분을 ‘가짜’ 버전(목)으로 만들어, 실제 파일이나 네트워크를 다루지 않고도 코드를 테스트할 수 있게 합니다.

사용하는 경우

  • ✓파일을 저장하거나 읽는 Swift 코드를 작성할 때.
  • ✓네트워크 오류에 코드가 어떻게 반응하는지 테스트해야 할 때.
  • ✓메인 앱과 테스트에서 서로 다른 방식으로 작동해야 하는 앱의 부분을 만들 때.

스킬 링크

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

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/swift-protocol-di-testing/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“실제로 파일을 저장하지 않고 파일에 데이터를 저장하는 코드를 어떻게 테스트할 수 있을까요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

외부 상호작용을 위한 작은 ‘규칙’(프로토콜)을 정의합니다. 그다음 일반 사용을 위한 실제 구현과 테스트를 위한 ‘가짜’ 구현을 만듭니다. 코드는 이 규칙을 사용하고, 테스트에서는 가짜 버전을 사용하도록 지정합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

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) {

…
자주 묻는 질문

이 맥락에서 ‘프로토콜’이란 무엇인가요?

코드가 무엇을 할 수 있는지는 정의하지만 정확히 어떻게 하는지는 말하지 않는 계약과 같습니다. 이를 통해 테스트에서 실제 구현을 가짜로 바꿀 수 있습니다.

‘의존성 주입’이란 무엇인가요?

코드가 필요한 부분(예: 파일 접근)을 스스로 만드는 대신 외부에서 제공받는 것입니다. 테스트용 가짜 버전으로 쉽게 교체할 수 있습니다.

‘목(mock)’을 사용하는 이유는 무엇인가요?

목은 코드의 가짜 버전입니다. 오류나 특정 데이터 같은 상황을 흉내 내어, 실제 환경에 의존하지 않고 통제된 방식으로 코드를 테스트하게 해 줍니다.

상세 정보

작성자의 원본 설명

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

인기도

GitHub 스타
280k
순위
#251
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬