如何解决如何在 iOS Swift 中模拟 Firebase RemoteConfig 进行测试?
我有一个接受 Firebase RemoteConfig 的函数
func myfunction(remoteConfig: RemoteConfig) -> String {
if (remoteConfig["my_value"].boolValue) {
return "ABC"
} else {
return "DEF"
}
}
我尝试模拟 RemoteConfig
,但不知道该怎么做。
我尝试如下,显然,它不起作用,并投诉
Cannot override 'init' which has been marked unavailable: Use +remoteConfig instead.
class MockRemoteConfig: RemoteConfig {
public init() {}
}
class FirebaseServicesSpec : QuickSpec {
override func spec() {
describe("myfunction") {
context("when my_value is not set") {
it("is should return DEF") {
expect(FirebaseServices.myfunction(
remoteConfig: MockRemoteConfig())).to(equal("DEF"))
}
}
}
}
}
如何在 Swift 中模拟 RemoteConfig? (在 Android 中,我只能使用 Mock()
)。
解决方法
我遇到了同样的问题,我发现这样做的唯一方法是生成一个协议,克隆我打算从 RemoteConfig
使用的方法的签名,在您的情况下,您只需要一个协议定义下标函数
protocol RemoteConfigProtocol {
func configValue(forKey key: String?) -> RemoteConfigValue // Used internally to fetch values
subscript(_ key: String?) -> RemoteConfigValue { get } // Used to index by key like remoteConfig[key]
}
extension RemoteConfigProtocol {
subscript(key: String?) -> RemoteConfigValue {
return self.configValue(forKey: key)
}
}
然后用它扩展 RemoteConfig
extension RemoteConfig: RemoteConfigProtocol {
// Already complies since we are cloning RemoteConfig signatures
}
之后你应该直接使用协议而不是RemoteConfig
func myfunction(remoteConfig: RemoteConfigProtocol) -> String {
if (remoteConfig["my_value"].boolValue) {
return "ABC"
} else {
return "DEF"
}
}
用于测试
class MockRemoteConfig: RemoteConfigProtocol {
// We have init available!
// Protocol stubs go here
}
希望你觉得这有用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。