claudegoodies
Skill

swift-protocol-di-testing

From affaan-m

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

Provides Swift patterns for protocol-based dependency injection to mock file system, network, and bookmark storage in tests.

Use it when

  • Writing Swift code that touches file system, network, or external APIs
  • Need to test error paths without triggering real I/O failures
  • Building modules that must run in app, test, and SwiftUI preview contexts
  • Using actors/Sendable and need mockable dependencies across boundaries

Skip it if

  • Swift-only; irrelevant for other languages
  • Just a documented pattern/style guide, not a library or tool
  • Mock classes shown are not thread-safe, limited to single-threaded tests

Facts

Repository
affaan-m/ECC
Status
Actively maintained
Last commit

Source preview

The instructions Claude Code reads when this skill runs.

# 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 f
View full source on GitHub →

Other skills