我正在编写一些单元测试,我需要创建一个 GIDGoogleUser 的模拟实例以确保我的 API 返回我的模型用户类的正确实例,它是 GIDGoogleUser 中字段的子集。
由于 GIDGoogleUser 没有公开初始值设定项,并且它的所有属性都是只读的,所以我无法创建模拟实例并将其注入(inject)到我的转换器中。我有什么办法可以做到这一点吗?
为简单起见,这就是我正在做的:
struct User {
let name: String
init(googleUser: GIDGoogleUser) {
name = googleUser.profile.name
}
}
最佳答案
当您说您不能模拟 GIDGoogleUser
时,我不确定您的意思。这是我刚才制作的 GIDGoogleUser
的模拟:
首先,声明 GIDGoogleUser
和 GIDProfileData
将遵守的协议(protocol),以及我们稍后将制作的模拟:
protocol GoogleUserProtocol {
associatedtype Profile: ProfileDataProtocol
var profile: Profile! { get }
}
protocol ProfileDataProtocol {
var name: String! { get }
}
然后,让 GIDGoogleUser
和 GIDProfileData
符合这些协议(protocol):
extension GIDGoogleUser: GoogleUserProtocol {}
extension GIDProfileData: ProfileDataProtocol {}
然后,创建我们的模拟类(或在本例中我选择的结构),并让它们符合上述协议(protocol):
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 实例并将它们注入(inject)到您的 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"
当然,您仍然可以使用“真实的”Google User 对象初始化您的 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
关于ios - 创建 GIDGoogleUser 的模拟实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58652749/