【问题标题】:How to mock CMMotionManager for Unit test如何模拟 CMMotionManager 进行单元测试
【发布时间】:2022-08-19 03:59:55
【问题描述】:

我的代码库将设备运动数据用于特定功能。我想对它进行单元测试。为此,我需要模拟 CMMotionManager 以便可以操作数据并根据要求执行测试用例。有没有办法实现这一目标?

需要模拟以下函数的回调

startDeviceMotionUpdates(to queue: OperationQueue, withHandler handler: @escaping CMDeviceMotionHandler)

    标签: swift unit-testing mocking cmmotionmanager


    【解决方案1】:

    有两种直接的方法可以用来模拟它;

    1. 子类化

      你可以继承CMMotionManager 并重载你想要模拟的函数。这将允许您在当前使用CMMotionManager 的任何地方注入模拟。

      class CMMotionManagerMock: CMMotionManager {
      
          override func startDeviceMotionUpdates(to queue: OperationQueue, withHandler handler: @escaping CMDeviceMotionHandler) {
              // Mock your desired functionality
          }
      }
      
      1. 协议和扩展

      使用协议时,您必须在整个代码库中使用该协议,以便能够在需要时注入模拟。这是一个抽象层,如果仅用于测试目的,可能会造成混淆。

      protocol DeviceMotionUpdatable {
          func startDeviceMotionUpdates(to queue: OperationQueue, withHandler handler: @escaping CMDeviceMotionHandler)
      }
      
      extension CMMotionManager: DeviceMotionUpdatable {}
      
      // The mock
      
      class CMMotionManagerMock: DeviceMotionUpdatable {
          func startDeviceMotionUpdates(to queue: OperationQueue, withHandler handler: @escaping CMDeviceMotionHandler) {
              // Mock your desired functionality
          }
      }
      
      // Implementation
      class Some {
         let motionManager: DeviceMotionUpdatable
      
         init(motionManager: DeviceMotionUpdatable = CMMotionManager()) {
            self.motionManager = self.motionManager
         }
      }
      
      // Call site
      Some() // Injects the real motion manager
      Some(motionManager: CMMotionManagerMock()) // injects the mock motion manager
      

    【讨论】:

    • 感谢您的出路,但我的问题是,如果您参考 CMMotionManager 类,则只有 { get } 属性。所以将无法为其设置虚拟值。
    • 在这种情况下,将CMMotionManager 所需的行为封装在您自己的类中,该类定义了您需要的所有行为。然后,您可以使用其中任何一种方法来模拟该类。
    猜你喜欢
    • 2018-04-04
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多