James Montemagno
James Montemagno

Live, Love, Bike, and Code.



Unit Testing Plugins for Xamarin

James MontemagnoJames Montemagno

So you love unit testing…. said no one ever, but you are forced to write unit tests and you want to use Plugins for Xamarin which are all singletons and need platform specific implementations or they will throw an exception in your tests…. what to do?!?!? Plugins are all interface based, which means all we have to do is use standard practices to not directly call the singleton, and setup our code to return the instance we want. In unit tests we can return a Mock (or Moq) of the interface, and in our standard code the singleton/

Let’s take the Connectivity Plugin (my most popular plugin), which checks for connectivity and event changes. There is no code that is laid down and you are encourage to use the singleton of CrossConnectivity.Current.IsConnected, but that would be an issue in a unit test project or installed into something else that it isn’t supported. Unless we structure our code a bit different like this:

This code is structured pretty well actually, and how I would encourage you to use Plugins, which is to just have a property that returns the single, or returns it from your Dependency Service/IoC. If we need to unit test this puppy all we need to do is change that get property to a get and set property and make it static so we can set it in our unit tests.

Now, all we need to do is simply create a mock that implements IConnectivity and then set it in our unit tests.

There you have it, you can install any plugin into any unit test project, but it may or may not have an implementation… and really you don’t want to rely on the implementation in the unit test project as you want full control. You can roll your own mocking framework or use one that is available. Just think of it as an interface.

Live, Love, Bike, and Code