What are mocking and stubbing techniques for Core Bluetooth in Swift?

Mocking and stubbing are essential techniques for unit testing in Swift applications that use Core Bluetooth. These techniques allow developers to simulate the behavior of Bluetooth peripherals and central managers without needing actual hardware. By using mocking and stubbing, tests can run faster and more reliably, as they are not dependent on the physical devices being available or in a particular state.

Mocking typically involves creating a fake version of an object that adheres to a specific protocol and captures interactions, while stubbing provides preset responses for method calls. In the context of Core Bluetooth, this becomes useful for simulating Bluetooth state changes, discovering services, and receiving characteristic updates.

Example of Mocking and Stubbing Core Bluetooth in Swift

// Mocking CBCentralManager to simulate Bluetooth interactions class MockCentralManager: CBCentralManager { var didDiscoverPeripheralCalled = false var discoveredPeripheral: CBPeripheral? func simulatePeripheralDiscovery(peripheral: CBPeripheral) { didDiscoverPeripheralCalled = true discoveredPeripheral = peripheral } } // Stubbing the peripheral with pre-defined characteristics class MockPeripheral: CBPeripheral { var mockedName: String init(name: String) { self.mockedName = name super.init() } override var name: String? { return mockedName } } // Unit test example func testPeripheralDiscovery() { let mockCentralManager = MockCentralManager() let mockPeripheral = MockPeripheral(name: "Test Peripheral") mockCentralManager.simulatePeripheralDiscovery(peripheral: mockPeripheral) XCTAssertTrue(mockCentralManager.didDiscoverPeripheralCalled) XCTAssertEqual(mockCentralManager.discoveredPeripheral?.name, "Test Peripheral") }

Mocking Stubbing Core Bluetooth Swift Testing Unit Testing Bluetooth Peripherals