Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create unit tests for functions that use Xamarin.Essentials: Geolocation API?

In my Locationer class I have function GetLocationAsync() which uses Xamarin.Essentials: Geolocation. This function works fine but I would like to create unit test for this function.

I created xUnitTests project and unit test:

public async Task LocationTest()
{
    Locationer locationer = new Locationer();
    var actual = locationer.GetLocationAsync();

    Assert.Equal("test", actual);
}

In Xamarin Forms project GetLocationAsync() returns "Latitude: 46.55465, Longitude: 15.64588, Altitude: 262".

In my unit tests GetLocationAsync() returns "This functionality is not implemented in the portable version of this assembly"

Is it possible to use Xamarin.Essentials: Geolocation in my Unit Tests project? How can I fix it?

like image 456
Mateusz Piwowarski Avatar asked Oct 26 '25 19:10

Mateusz Piwowarski


1 Answers

Ryan Davis has created interfaces based on Xamarin.Essentials: https://www.nuget.org/packages/Xamarin.Essentials.Interfaces/

This way you can register Essentials implementations in your IoC container:

builder.Register<IGeolocation, GeolocationImplementation>();

And you would be able to Mock the interfaces with something like Moq:

var mockGeo = new Mock<IGeolocation>();
mockGeo.Setup(x => x.GetLocationAsync())
   .ReturnsAsync(() => new Location());
like image 171
Cheesebaron Avatar answered Oct 28 '25 10:10

Cheesebaron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!