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.
// 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")
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?