gpt4 book ai didi

swift - 依赖注入(inject) : static methods and parameters

转载 作者:行者123 更新时间:2023-11-28 14:48:36 32 4
gpt4 key购买 nike

我正在尝试向分层在 Objective-C 库上的 Swift 程序添加单元测试。我目前的主要问题是找到一种方法来注入(inject)使用参数化静态工厂方法创建的依赖项。

例如,以下代码是功能性的,但更耐测试:

class Processor {
var service: RegistrationService?

func register(user: String, pass: String) {
let configuration = Configuration(user: user, pass: pass)
service = RegistrationServiceProvider.registrationService(configuration: configuration)

// Do various things with the 'service'
}
}

请注意,RegistrationServiceProviderRegistrationServiceConfiguration 均来自 Objective-C 库。

我希望能够做的是提供在此代码中创建的 RegistrationService 作为默认值,并在测试时将其替换为我自己的模拟。如果没有 Configuration 对象,使用类似 http://www.danielhall.io/swift-y-dependency-injection-part-two 的东西会相当简单.

(我意识到我可以/应该将 Configuration 构造推送给调用者,但这并没有解决如何将它提供给默认服务的问题。)

欢迎提出建议和引用。

最佳答案

您可以创建 RegistrationService 和 RegistrationServiceProvider 的模拟并将它们注入(inject)测试,使用标准类型作为正常调用中的默认类型,如下面的代码(它包括您使用的类的示例版本和一些打印出来看看叫什么):

class Configuration {
let user: String
let pass: String

init(user: String, pass: String) {
self.user = user
self.pass = pass
}
}

class RegistrationService {
let configuration: Configuration

init(configuration: Configuration) {
self.configuration = configuration
}
}

class RegistrationServiceProvider {

class func registrationService(configuration: Configuration) -> RegistrationService {
print("Provider instantiated service")
return RegistrationService(configuration: configuration)
}
}

class Processor {
var service: RegistrationService?
func register(user: String, pass: String, serviceProvider: RegistrationServiceProvider.Type = RegistrationServiceProvider.self) {
let configuration = Configuration(user: user, pass: pass)
service = serviceProvider.registrationService(configuration: configuration)

// Do various things with the 'service'
}
}

class MockProvider: RegistrationServiceProvider {
override class func registrationService(configuration: Configuration) -> RegistrationService {
print("Mock provider instantiated mock service")
return MockService(configuration: configuration)
}
}

class MockService: RegistrationService {
override init(configuration: Configuration) {
super.init(configuration: configuration)
print("Mock service initialized")
}
}

let processor = Processor()

processor.register(user: "userName", pass: "myPassword") // Provider instantiated service

processor.register(user: "userName", pass: "myPassword", serviceProvider: MockProvider.self) // Mock provider instantiated mock service

关于swift - 依赖注入(inject) : static methods and parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50066469/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com