Swift Protocol-Based DI for Testing

VerifiedSafe

Protocol-based dependency injection for testable Swift code — mock file system, network, and external APIs using focused protocols and Swift Testing.

Sby Skills Guide Bot
TestingIntermediate
8/29/2026
Claude CodeCursorCodex
#swift#dependency-injection#mocking#unit-testing#swift-testing

Recommended for

Automated summary

Describes protocol-based dependency injection patterns for making Swift code testable by abstracting the file system, network, and external APIs behind small focused protocols and mocks.

Strengths

  • Walks through the full loop: focused protocol, default production implementation, mock, and injection via default parameters
  • Accounts for Swift concurrency concerns (actors, Sendable, @unchecked Sendable mocks)
  • Lets you exercise error-handling paths without triggering real I/O
  • Uses Swift Testing with @Test-style test functions and descriptive names

Limitations

  • Mocks are hand-written; no mocking framework or generation tooling is covered
  • Focuses on file system/iCloud and network dependencies, not SwiftUI views or UI tests
  • Assumes you can change initializers of the code under test to accept injected protocols
When to use it

Use it when writing Swift code that touches the disk, network, or external APIs and you want deterministic tests without real I/O.

When not to use it

Avoid it when the code under test cannot accept injected dependencies, or when the need is SwiftUI UI testing rather than dependency isolation.

Security analysis

Safe
Quality score85/100

This skill is purely instructional documentation about Swift dependency-injection and testing patterns. It declares no tools, contains no shell commands, network calls, file exfiltration, obfuscated payloads, or destructive operations. The example code only demonstrates in-memory mock implementations and protocol abstractions, so there is no meaningful execution risk.

No concerns found

How this analysis is made

Examples

Make a sync manager testable
This Swift SyncManager reads iCloud files directly with FileManager and Data(contentsOf:). Refactor it to use small protocols for file system and file access with default production implementations, then inject a mock in tests.
Test error paths without real failures
Write Swift Testing tests that make the file read throw CocoaError(.fileReadNoSuchFile) and verify my SyncManager surfaces the right error, using a mock file accessor instead of touching disk.
Design Sendable-safe mocks
My actor-based Swift service depends on a network client. Show me which protocols should be Sendable and how to write a mock implementation that works inside an actor under Swift concurrency.

name: swift-protocol-di-testing description: 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. metadata: origin: ECC

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) {
        try await manager.sync()
    }
}

Best Practices

  • Single Responsibility: Each protocol should handle one concern — don't create "god protocols" with many methods
  • Sendable conformance: Required when protocols are used across actor boundaries
  • Default parameters: Let production code use real implementations by default; only tests need to specify mocks
  • Error simulation: Design mocks with configurable error properties for testing failure paths
  • Only mock boundaries: Mock external dependencies (file system, network, APIs), not internal types

Anti-Patterns to Avoid

  • Creating a single large protocol that covers all external access
  • Mocking internal types that have no external dependencies
  • Using #if DEBUG conditionals instead of proper dependency injection
  • Forgetting Sendable conformance when used with actors
  • Over-engineering: if a type has no external dependencies, it doesn't need a protocol

When to Use

  • Any Swift code that touches file system, network, or external APIs
  • Testing error handling paths that are hard to trigger in real environments
  • Building modules that need to work in app, test, and SwiftUI preview contexts
  • Apps using Swift concurrency (actors, structured concurrency) that need testable architecture

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/swift-protocol-based-di-for-testing-mte1lkrm/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/swift-protocol-based-di-for-testing-mte1lkrm' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/swift-protocol-based-di-for-testing-mte1lkrm/download' --output '.skill-downloads/swift-protocol-based-di-for-testing-mte1lkrm/SKILL.md.part' && mv '.skill-downloads/swift-protocol-based-di-for-testing-mte1lkrm/SKILL.md.part' '.skill-downloads/swift-protocol-based-di-for-testing-mte1lkrm/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/swift-protocol-based-di-for-testing-mte1lkrm/SKILL.md' && test -s '.skill-downloads/swift-protocol-based-di-for-testing-mte1lkrm/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/swift-protocol-di-testing' && cp -R '.skill-downloads/swift-protocol-based-di-for-testing-mte1lkrm' '.claude/skills/swift-protocol-di-testing'

Cursor
test -f '.skill-downloads/swift-protocol-based-di-for-testing-mte1lkrm/SKILL.md' && test -s '.skill-downloads/swift-protocol-based-di-for-testing-mte1lkrm/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/swift-protocol-di-testing' && cp -R '.skill-downloads/swift-protocol-based-di-for-testing-mte1lkrm' '.cursor/skills/swift-protocol-di-testing'

Codex
test -f '.skill-downloads/swift-protocol-based-di-for-testing-mte1lkrm/SKILL.md' && test -s '.skill-downloads/swift-protocol-based-di-for-testing-mte1lkrm/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/swift-protocol-di-testing' && cp -R '.skill-downloads/swift-protocol-based-di-for-testing-mte1lkrm' '.agents/skills/swift-protocol-di-testing'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/swift-protocol-based-di-for-testing-mte1lkrm'

openskills read 'swift-protocol-based-di-for-testing-mte1lkrm'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/swift-protocol-based-di-for-testing-mte1lkrm/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills