我不确定你说你不能模拟 GIDGoogleUser 是什么意思。这是我刚刚制作的GIDGoogleUser 的模拟:
首先,声明GIDGoogleUser 和GIDProfileData 将遵循的协议,以及稍后我们将制作的模拟:
protocol GoogleUserProtocol {
associatedtype Profile: ProfileDataProtocol
var profile: Profile! { get }
}
protocol ProfileDataProtocol {
var name: String! { get }
}
然后,让GIDGoogleUser 和GIDProfileData 符合这些协议:
extension GIDGoogleUser: GoogleUserProtocol {}
extension GIDProfileData: ProfileDataProtocol {}
然后,创建我们的模拟类(或我在本例中选择的结构),并让它们符合上述协议:
struct MockGoogleUser: GoogleUserProtocol {
let profile: MockProfileData!
}
struct MockProfileData: ProfileDataProtocol {
let name: String!
}
最后,调整 User 的初始化器,使其不采用 GIDGoogleUser,而是采用符合 GoogleUserProtocol 的任何内容:
struct User {
let name: String
init<G>(googleUser: G) where G: GoogleUserProtocol {
name = googleUser.profile.name
}
}
这将让您创建模拟 Google 用户实例并将它们注入您的 User,如下所示:
let mockProfileData = MockProfileData(name: "Mock User Name")
let mockGoogleUser = MockGoogleUser(profile: mockProfileData)
let mockUser = User(googleUser: mockGoogleUser)
print(mockUser.name) // prints "Mock User Name"
当然你也可以用“真实的”谷歌用户对象来初始化你的User:
let realGoogleUser: GIDGoogleUser = ... // get a GIDGoogleUser after signing in
let realUser = User(googleUser: realGoogleUser)
print(realUser.name) // prints whatever the real GIDGoogleUser's name is