Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a test trait for dependency key. #308

Merged
merged 6 commits into from
Nov 15, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Sources/DependenciesTestSupport/TestTrait.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,40 @@
Self { $0[keyPath: keyPath] = value }
}

/// A trait that overrides a test's or suite's dependency.
///
/// Useful for overriding a dependency in a test without incurring the nesting and
/// indentation of ``withDependencies(_:operation:)-4uz6m``.
///
/// ```swift
/// struct Client: DependencyKey { … }
/// @Test(
/// .dependency(Client.mock)
/// )
/// func feature() {
/// // ...
/// }
/// ```
///
/// > Important: Due to [a Swift bug](https://github.com/swiftlang/swift/issues/76409), it is
/// > not possible to specify a closure directly inside a `@Suite` or `@Test` macro:
/// >
/// > ```swift
/// > @Suite(
/// > .dependency(Client { _ in .mock }) // 🛑
/// > )
/// > struct FeatureTests { /* ... */ }
/// > ```
///
/// - Parameters:
/// - keyPath: A key path to a dependency value.
/// - value: A dependency value to override for the test.
public static func dependency<Value: TestDependencyKey>(
_ value: Value
) -> Self where Value == Value.Value {
Self { $0[Value.self] = value }
}

/// A trait that overrides a test's or suite's dependencies.
public static func dependencies(
_ updateValues: @escaping @Sendable (inout DependencyValues) -> Void
Expand Down
7 changes: 7 additions & 0 deletions Tests/DependenciesTests/SwiftTestingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,13 @@
}
}
}

private static let mockClient = Client { 42 }
@Test(.dependency(mockClient))
func dependencyKeyTypeTrait() {
@Dependency(Client.self) var client
#expect(client.increment() == 42)
}
}

private struct Client: TestDependencyKey {
Expand Down