需要模拟 Firebase Auth 但不确定如何

Tom*_*you 6 ios firebase swift firebase-authentication

我使用 Firebase 在我的应用程序中管理身份验证。这有一个登录用户的单例对象:Auth.auth().currentUser

在我的部分代码中,我检查uid登录用户的 等于userId与对象关联的 。

我需要测试使用此检查的代码。为此,我需要能够注入模拟 Firebase Auth 对象。

如何模拟 Firebase Auth 对象?有没有人有过这方面的经验?

Tom*_*you 3

因此,我通过创建一些身份验证协议并使其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>)