【问题标题】:Creating mock instances of GIDGoogleUser创建 GIDGoogleUser 的模拟实例
【发布时间】:2020-02-27 08:50:28
【问题描述】:

我正在编写一些单元测试,我需要创建一个 GIDGoogleUser 的模拟实例,以确保我的 API 返回我的模型 User 类的正确实例,它是 GIDGoogleUser 中字段的子集。

由于 GIDGoogleUser 没有公开初始化程序,并且它的所有属性都是只读的,因此我无法创建模拟实例并将其注入到我的转换器中。有什么办法可以做到吗?

为简单起见,这就是我正在做的:

struct User {
  let name: String

  init(googleUser: GIDGoogleUser) {
    name = googleUser.profile.name
  }
}

【问题讨论】:

    标签: ios swift google-signin xctest


    【解决方案1】:

    我不确定你说你不能模拟 GIDGoogleUser 是什么意思。这是我刚刚制作的GIDGoogleUser 的模拟:

    首先,声明GIDGoogleUserGIDProfileData 将遵循的协议,以及稍后我们将制作的模拟:

    protocol GoogleUserProtocol {
        associatedtype Profile: ProfileDataProtocol
        var profile: Profile! { get }
    }
    
    protocol ProfileDataProtocol {
        var name: String! { get }
    }
    

    然后,让GIDGoogleUserGIDProfileData 符合这些协议:

    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
    

    【讨论】:

      猜你喜欢
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 2022-11-21
      相关资源
      最近更新 更多