Tom*_*you 6 ios firebase swift firebase-authentication
我使用 Firebase 在我的应用程序中管理身份验证。这有一个登录用户的单例对象:Auth.auth().currentUser
在我的部分代码中,我检查uid
登录用户的 等于userId
与对象关联的 。
我需要测试使用此检查的代码。为此,我需要能够注入模拟 Firebase Auth 对象。
如何模拟 Firebase Auth 对象?有没有人有过这方面的经验?
因此,我通过创建一些身份验证协议并使其User
符合该协议来解决这个问题:
protocol AuthUser {
var uid: String {get}
var displayName: String? {get}
var email: String? {get}
var photoURL: URL? {get}
}
extension User : AuthUser {}
protocol AuthenticationProtocol {
var currentUser: AuthUser? {get}
}
Run Code Online (Sandbox Code Playgroud)
然后我创建了一个Authentication
符合以下要求的类AuthenticationProtocol
:
final class Authentication: AuthenticationProtocol {
static let shared = Authentication()
private let auth = Auth.auth()
var currentUser: AuthUser? {
return auth.currentUser
}
}
Run Code Online (Sandbox Code Playgroud)
当我的应用程序中有一个需要身份验证的类时,我注入一个符合AuthenticationProtocol
以下要求的类:
final class MyClass {
private let auth: AuthenticationProtocol
init(auth: AuthenticationProtocol = Authentication.shared) {
self.auth = auth
}
}
Run Code Online (Sandbox Code Playgroud)
然后我可以通过调用 来获取当前登录用户的 id auth.currentUser?.uid
。
对于测试,我然后创建一个符合AuthenticationProtocol
以下要求的模拟类:
final class AuthenticationMock : AuthenticationProtocol {
private let uid: String
let currentUser: AuthUser?
init(currentUser: AuthUser) {
self.currentUser = currentUser
}
}
Run Code Online (Sandbox Code Playgroud)
然后我可以在打电话时注入MyClass(auth: <Authentication Mock Instance>)
归档时间: |
|
查看次数: |
1398 次 |
最近记录: |