How do you mock platform/device services for testing?
Short answer
Abstract device features behind interfaces (e.g., IGeolocation, IConnectivity—MAUI already provides interfaces for many Essentials APIs) and inject them. In tests supply fakes/mocks.
Advertisement
AModel answer
Abstract device features behind interfaces (e.g., IGeolocation, IConnectivity—MAUI already provides interfaces for many Essentials APIs) and inject them. In tests supply fakes/mocks. Avoid calling static Essentials members directly in logic; depend on the interface so tests don't touch real hardware.
// Production: inject IConnectivity; Test: pass a stub
public SyncViewModel(IConnectivity connectivity) => _c = connectivity;
var vm = new SyncViewModel(new StubConnectivity(NetworkAccess.None));Real-world example
A sync view model is tested for its offline path by injecting a stub connectivity that reports no network.
Likely follow-ups
- Do Essentials expose interfaces? | Why avoid static calls in logic?
Related topics