Mocking Bluetooth in Flutter
How to test Bluetooth app without Bluetooth?
Note: There is an updated version of this article here
My app communicates with a BLE device, gets data and analyzes it, and performs actions based on the result. Testing the analysis and actions was relatively easy by loading the data from a file. Flutter has an excellent Mockito tutorial. But I wanted to test the startup flow, and for that I needed to simulate Bluetooth devices and streams.
How? That’s what we’re here for :)
Startup flow
This is the startup flow of my app:
Ideally, I would like to automatically pair with the last device. If there is no last device or if I can’t find it, I search for any device with name “MyDevice”. If I find such a device, I ask the user if to connect. If yes, then great! Otherwise, I need to search for another device with name MyDevice. And so on.
So I need to mock the Bluetooth scan; I need to Mock devices that match the last device and devices that don’t match the last device. I can’t mock them directly (I don’t want to in any case, that’s a LOT of classes) because e.g. a ScanResult has no constructor. What now?
Mockito to the rescue!