Skip to main content
Agent skill

Swift Protocol Di Testing

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.

Get started

Get the complete skill folder, including its scripts and reference files.

·

When to use this skill

Use Swift Protocol Di Testing when an AI agent needs a reusable SKILL.md workflow for this job: 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.

When not to use it

Skip Swift Protocol Di Testing when the task is outside the coding category, or when a more specific skill in this directory already covers the same workflow with clearer triggers.

How to install

Where will you use it?

Install scope
Claude Code folder setup
mkdir -p ~/.claude/skills/swift-protocol-di-testing
# Save SKILL.md to ~/.claude/skills/swift-protocol-di-testing/SKILL.md
  1. Claude Code personal install: place the skill and its bundled files at ~/.claude/skills/swift-protocol-di-testing/SKILL.md. For a shared project, commit the folder at .claude/skills/swift-protocol-di-testing/ instead.
  2. Current Claude Code detects SKILL.md changes in watched directories during the session. If you just created a top-level skills directory, run /reload-skills. Check that the skill is listed before testing its trigger.
  3. For Claude chat or Cowork in the Desktop app, manage uploaded skills in Customize > Skills; copying files into a local Claude Code folder is not a Desktop install. Other agents may use different install locations.

Full install guide for Claude, Cursor, and Codex →

Try a starter prompt

After installing the skill, paste this starter prompt into your agent to verify it triggers on a small task.

Starter prompt
Use the Swift Protocol Di Testing skill for this task: Any Swift code that touches file system, network, or external APIs. Confirm any required inputs or files before making changes.

What supports this recommendation?

88/100 provisional content score. This measures documentation, practical detail and source signals. It is not a measured task success rate or a security certification.

Documentation
100/100
Practical detail
100/100
Source evidence
63/100
Source signals
72/100
Model compatibility evidence
  • claudeuntested

    No model-specific signal or recorded compatibility test was found.

  • chatgptuntested

    No model-specific signal or recorded compatibility test was found.

  • geminiuntested

    No model-specific signal or recorded compatibility test was found.

  • copilotuntested

    No model-specific signal or recorded compatibility test was found.

  • llamauntested

    No model-specific signal or recorded compatibility test was found.

  • perplexityuntested

    No model-specific signal or recorded compatibility test was found.

  • mistraluntested

    No model-specific signal or recorded compatibility test was found.

  • grokuntested

    No model-specific signal or recorded compatibility test was found.

Inferred compatibility is based on content signals. Check the app, its available tools and setup requirements before running a skill.

What this skill does

# 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.

```swift // 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

```swift 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

```swift 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.

```swift 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

```swift 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

Intended uses

  • 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

Implementation notes

  • 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

Try it, then tell us how it went

A copied prompt does not tell us whether the task worked. Report your result after checking the output. We collect your tool and outcome, never your files or prompt.