[Feature] Dependencies #3

Merged
javier merged 5 commits from feature/dependencies into main 2023-04-16 15:36:08 +00:00
3 changed files with 119 additions and 0 deletions
Showing only changes of commit dd416a85a1 - Show all commits

View File

@ -0,0 +1,28 @@
//
// DependencyService.swift
// Dependencies
//
// Created by Javier Cicchelli on 11/04/2023.
// Copyright © 2023 Röck+Cöde. All rights reserved.
//
/// This service provide write/read access to the injected dependencies.
public struct DependencyService {
// MARK: Properties
private static var current = DependencyService()
// MARK: Subscripts
public static subscript<DK: DependencyKey>(key: DK.Type) -> DK.Value {
get { key.currentValue }
set { key.currentValue = newValue }
}
public static subscript<D>(_ keyPath: WritableKeyPath<DependencyService, D>) -> D {
get { current[keyPath: keyPath] }
set { current[keyPath: keyPath] = newValue }
}
}

View File

@ -0,0 +1,34 @@
//
// TestServices.swift
// DependenciesTests
//
// Created by Javier Cicchelli on 11/04/2023.
// Copyright © 2023 Röck+Cöde. All rights reserved.
//
import Dependencies
// MARK: - Protocols
protocol TestService {}
// MARK: - Services
struct SomeService: TestService, Equatable {}
struct SomeOtherService: TestService, Equatable {}
// MARK: - DependencyKey
struct TestServiceKey: DependencyKey {
static var currentValue: TestService = SomeService()
}
// MARK: - DependencyService+Keys
extension DependencyService {
var testService: TestService {
get { Self[TestServiceKey.self] }
set { Self[TestServiceKey.self] = newValue }
}
}

View File

@ -0,0 +1,57 @@
//
// DependencyServiceTests.swift
// DependenciesTests
//
// Created by Javier Cicchelli on 11/04/2023.
// Copyright © 2023 Röck+Cöde. All rights reserved.
//
import Dependencies
import XCTest
final class DependencyServiceTests: XCTestCase {
// MARK: Setup
override func setUp() {
DependencyService[\.testService] = SomeService()
}
// MARK: Tests
func test_readDependencyKey() async throws {
// GIVEN
// WHEN
let service = DependencyService[\.testService]
// THEN
XCTAssertNotNil(service)
XCTAssert(service is SomeService)
}
func test_writeDependencyKey() async throws {
// GIVEN
DependencyService[\.testService] = SomeOtherService()
// WHEN
let service = DependencyService[\.testService]
// THEN
XCTAssertNotNil(service)
XCTAssert(service is SomeOtherService)
}
func test_writeDependencyKeyTwice() async throws {
// GIVEN
DependencyService[\.testService] = SomeOtherService()
DependencyService[\.testService] = SomeService()
// WHEN
let service = DependencyService[\.testService]
// THEN
XCTAssertNotNil(service)
XCTAssert(service is SomeService)
}
}