swift-protocol-di-testing
Skill1 starsChanged 8 months agoMITView on GitHub
Protocol-based dependency injection for testable Swift code — mock file system, network, and external APIs using focused protocols and Swift Testing.
Files
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 DEBUGconditionals instead of proper dependency injection - Forgetting
Sendableconformance 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
Other versions15 projects use a version of this.
Word for word · 10
- loulanyue/awesome-claude-notes★ 272100% same
- junimnjw/everything-claude-code★ 1100% same
- SamuelNDCE/claude-super-skill-library★ 1100% same
- TironFox/everything-claude-code★ 1100% same
- davidanthonyn/claude-skills★ 0100% same
- gesh75/claude-skills★ 0100% same
- MohamedEssam0-0/claude-skills★ 0100% same
- PeterYang888/claude-skills★ 0100% same
- ramybarsoum/claude-skills★ 0100% same
- Tom1tk/claude-skills★ 0100% same
Edited · 5
- Fmarzochi/EGC★ 6199% same
- gongyijie85/dsh-ecc★ 897% same
- ronmkr/PromptBook★ 299% same
- TsinHzl/claude-code-config★ 262% same
- renepf/claude-skills★ 099% same
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
Used alongsideProjects with it also use nuxt4-patterns, ralphinho-rfc-pipeline and 10 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
loulanyueSkillnuxt4-patterns
Nuxt 4 app patterns for hydration safety, performance, route rules, lazy loading, and SSR-safe data fetching with useFetch and useAsyncData.
Also in 7 projects that use this
junimnjwSkillralphinho-rfc-pipeline
RFC-driven multi-agent DAG execution pattern with quality gates, merge queues, and work unit orchestration.
Also in 8 projects that use this
loulanyueSkillsanta-method
Multi-agent adversarial verification with convergence loop. Two independent review agents must both pass before output ships.
Also in 5 projects that use this
junimnjwSkillcarrier-relationship-management
Codified expertise for managing carrier portfolios, negotiating freight rates, tracking carrier performance, allocating freight, and maintaining strategic carrier relationships. Informed by transportation managers with 15+ years experience. Includes scorecarding frameworks, RFP processes, market intelligence, and compliance vetting. Use when managing carriers, negotiating rates, evaluating carrier performance, or building freight strategies.
Also in 5 projects that use this
Yog-SothoSkillpytorch-patterns
PyTorch deep learning patterns and best practices for building robust, efficient, and reproducible training pipelines, model architectures, and data loading. Always activate when the user is writing PyTorch models or training scripts, reviewing deep learning code, debugging training loops or data pipelines, optimizing GPU memory or training speed, setting up reproducible experiments, implementing transfer learning or fine-tuning, or asks anything about nn.Module, DataLoader, autograd, AMP, or torch.compile.
Also in 7 projects that use this
TironFoxSkillagent-payment-x402
Add x402 payment execution to AI agents — per-task budgets, spending controls, and non-custodial wallets via MCP tools. Use when agents need to pay for APIs, services, or other agents.
Also in 3 projects that use this
- +6 more from junimnjw
In this repository71 other files it gives its agents.
- .claude/rules/common/agents.mdAGENTS.md
- docs/agents.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- api-designSkill
- article-writingSkill
- backend-patternsSkill
- clickhouse-ioSkill
- coding-standardsSkill
- configure-eccSkill
- content-engineSkill
- content-hash-cache-patternSkill
- continuous-learningSkill
- continuous-learning-v2Skill
- cost-aware-llm-pipelineSkill
- cpp-coding-standardsSkill
- cpp-testingSkill
- database-migrationsSkill
- deployment-patternsSkill
- django-patternsSkill
- django-securitySkill
- django-tddSkill
- django-verificationSkill
- docker-patternsSkill
- e2e-testingSkill
- eval-harnessSkill
- foundation-models-on-deviceSkill
- frontend-patternsSkill
- frontend-slidesSkill
- golang-patternsSkill
- golang-testingSkill
- investor-materialsSkill
- investor-outreachSkill
- iterative-retrievalSkill
- java-coding-standardsSkill
- jpa-patternsSkill
- liquid-glass-designSkill
- market-researchSkill
- nutrient-document-processingSkill
- postgres-patternsSkill
- project-guidelines-exampleSkill
- python-patternsSkill
- python-testingSkill
- regex-vs-llm-structured-textSkill
- search-firstSkill
- security-reviewSkill
- security-scanSkill
- seo-auditSkill
- seo-competitor-pagesSkill
- seo-contentSkill
- seo-geoSkill
- seo-hreflangSkill
- seo-imagesSkill
- seo-pageSkill
- seo-planSkill
- seo-programmaticSkill
- seo-schemaSkill
- seo-sitemapSkill
- seoSkill
- seo-technicalSkill
- skill-stocktakeSkill
- The first 60 shown.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

