diff --git a/Sources/DependenciesTestSupport/TestTrait.swift b/Sources/DependenciesTestSupport/TestTrait.swift index eb06912e..bdce1bb7 100644 --- a/Sources/DependenciesTestSupport/TestTrait.swift +++ b/Sources/DependenciesTestSupport/TestTrait.swift @@ -43,10 +43,10 @@ /// - value: A dependency value to override for the test. public static func dependency( _ keyPath: WritableKeyPath & Sendable, - _ value: sending Value + _ value: @escaping @Sendable @autoclosure () -> Value ) -> Self { - Self { [uncheckedValue = UncheckedSendable(value)] in - $0[keyPath: keyPath] = uncheckedValue.wrappedValue + Self { + $0[keyPath: keyPath] = value() } } @@ -79,9 +79,9 @@ /// - keyPath: A key path to a dependency value. /// - value: A dependency value to override for the test. public static func dependency( - _ value: Value + _ value: @escaping @Sendable @autoclosure () -> Value ) -> Self where Value == Value.Value { - Self { $0[Value.self] = value } + Self { $0[Value.self] = value() } } /// A trait that overrides a test's or suite's dependencies. diff --git a/Tests/DependenciesTests/SwiftTestingTests.swift b/Tests/DependenciesTests/SwiftTestingTests.swift index ef45b7c3..6bb29e8f 100644 --- a/Tests/DependenciesTests/SwiftTestingTests.swift +++ b/Tests/DependenciesTests/SwiftTestingTests.swift @@ -92,6 +92,43 @@ import ConcurrencyExtras func dependencyKeyNonSendableValue() { // NB: This test is to prove this trait compiles with a non-sendable type. } + + // NB: This is to prove that a new instance of the dependency is used for each test. + struct NewClassInstanceSuite { + @Suite(.serialized, .dependency(\.classClient, ClassClient())) + struct DependencyValues { + @Test + func test1() { + @Dependency(\.classClient) var client + client.count += 1 + #expect(client.count == 1) + } + + @Test + func test2() { + @Dependency(\.classClient) var client + client.count += 1 + #expect(client.count == 1) + } + } + + @Suite(.serialized, .dependency(SendableClassClient())) + struct DependencyKey { + @Test + func test1() { + @Dependency(SendableClassClient.self) var client + client.count.withValue { $0 += 1 } + #expect(client.count.value == 1) + } + + @Test + func test2() { + @Dependency(SendableClassClient.self) var client + client.count.withValue { $0 += 1 } + #expect(client.count.value == 1) + } + } + } } private struct Client: TestDependencyKey { @@ -107,6 +144,10 @@ import ConcurrencyExtras } } + private final class SendableClassClient: TestDependencyKey, Sendable { + static var testValue: SendableClassClient { .init() } + let count = LockIsolated(0) + } class ClassClient { var count = 0 }