dev*_*ush 10 unit-testing dependency-injection xctest swift swift-protocols
我是一名经验丰富的Objective-c程序员,但我不能对Swift说同样的话,我很难在不使用像OCMock这样的框架的情况下在swift中测试一个类.
问题:我正在将Firebase集成到一个混合的Objective-C/Swift项目中,我需要根据应用程序的构建配置对其进行配置.
我为此编写了一个Swift类(将由obj-c app委托使用),但是由于firebase框架是通过静态类方法配置的FIRApp.configure(with: FIROptions),所以我需要以某种方式模拟这个方法以进行单元测试它.
我的代码,没有任何处理依赖注入,看起来像这样:
@objc class FirebaseConfigurator: NSObject{
func configureFirebase(){
let config = configManager.buildConfiguration
var optionsPlistBaseName = getPlistName()
let optionsFile = Bundle.main.path(forResource: optionsPlistBaseName, ofType: "plist")
guard let opts = FIROptions(contentsOfFile: optionsFile) else{
assert(false, "fatal: unable to load \(optionsFile)")
return
}
FIRApp.configure(with: opts)
}
func getPlistName() -> String{
// retrieves correct plist name and returns it
}
}
Run Code Online (Sandbox Code Playgroud)
我做了一些研究,但到目前为止我没有发现任何适合我的解决方案,但我想到的是以下其中一项:
FIRApp.configure(with:)但是我应该从objective-c执行此操作并且函数也接受一个参数,我正在努力学习语法作为参考(个人和可能需要它的人),这些是我认为有用的一些资源,我将继续挖掘:
同时,每一个帮助都会非常感激.
作为旁注,有很多方法可以解决这个问题而不用嘲笑静态类方法,但我的目标是找到一种嘲弄它的方法,以便在测试更复杂时更好地理解最佳实践的情况.
你确实可以做到其中任何一个。
\n\n您可以让您的configureFirebase函数采用默认为您最初使用的“应用程序”闭包:
func configureFirebase(\n using apply: (_ options: FIROptions) -> Void\n = { opts in FIRApp.configure(opts) }\n) {\n // building |opts| as before\n // Now replace this: FIRApp.configure(with: opts)\n apply(opts)\n}\nRun Code Online (Sandbox Code Playgroud)\n\n您需要一个Configurable协议,然后FIRApp在默认情况下遵守它:
protocol Configurable {\n static func configure(with options: FIROptions)\n}\n\nextension FIRApp: Configurable {}\n\nclass FirebaseConfigurator {\n var configurable: Configurable\n init(configurable: Configurable = FIRApp) {\n self.configurable = configurable\n }\n\n func configureFirebase() {\n //load |opts|\xe2\x80\xa6\n configurable.configure(with: opts)\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n但是,如果您只想在一种方法中使用它,那么它只是瞬态,并且它可能应该是函数参数而不是存储的属性。
\n\n(如果不清楚它是持久状态还是瞬态,因为类的全部目的是调用单个函数,也许您甚至不需要类,只需要一个函数。)
\n| 归档时间: |
|
| 查看次数: |
1909 次 |
| 最近记录: |