模拟 GMSPlace

问题描述 投票:0回答:1

我目前正在使用 Google Places,并创建了一个抽象的地点选择器,也是使用 Google Places 的具体实现。

我正在为它做一些单元测试。来到了我要mock GMSPlace的步骤(https://developers.google.com/places/ios-sdk/reference/interface_g_m_s_place

问题是 GMSPlace 类默认初始化不可用。

/**
 * Default init is not available.
 */
- (instancetype)init NS_UNAVAILABLE; 

有人可以分享我们如何在 init 不可用的情况下模拟事物吗?

谢谢

ios swift unit-testing mocking google-places
1个回答
0
投票

这可能是测试 GMSPlace 的替代方法。因此,GMSPlace 是适用于 iOS 的 Google Places API 中的一个类。它代表一个特定的地方,包括它的名称、地址和其他详细信息。如果您想模拟 GMSPlace 进行测试,您可以使用依赖注入和协议。

1 - 创建一个协议,代表您需要从 GMSPlace 获得的必要属性和方法。

 protocol Place {
    var name: String { get }
    var placeID: String { get }
    // Add other properties and methods you need
 }

2 - 创建一个符合 Place 协议的模拟类。

class MockPlace: Place {
    var name: String
    var placeID: String
    // Add other properties and methods you need
        
    init(name: String, placeID: String) {
      self.name = name
      self.placeID = placeID
    }
}

3- 扩展 GMSPlace 类以符合您的 Place 协议。

extension GMSPlace: Place {
    // GMSPlace already provides the required properties and methods,
    // so you don't need to add anything here.
}

4- 修改您的代码以依赖于 Place 协议而不是直接依赖于 GMSPlace 类。这允许您在代码中使用真实的 GMSPlace 对象或 MockPlace 对象,使其更易于测试。

class MyViewController: UIViewController {
 var selectedPlace: Place?

 func didSelectPlace(place: Place) {
    selectedPlace = place
    // Do something with the selected place
 }
}

5- 现在您可以使用 MockPlace 类进行测试。

func testDidSelectPlace() {
 let myViewController = MyViewController()
 let mockPlace = MockPlace(name: "Test Place", placeID: "123456")

 myViewController.didSelectPlace(place: mockPlace)

 XCTAssertEqual(myViewController.selectedPlace?.name, "Test Place")
 XCTAssertEqual(myViewController.selectedPlace?.placeID, "123456")
}
© www.soinside.com 2019 - 2024. All rights reserved.