4

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?

JackSparrow
  • 11
  • 1
  • 3
Mateusz Piwowarski
  • 559
  • 1
  • 6
  • 15

1 Answers1

6

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());
Cheesebaron
  • 24,131
  • 15
  • 66
  • 118
  • wow, I haven't heard anything about IoC containers and mocking before so I have to read something about it asap. Thank you for help. I hope it will work. Last question: Should I implement "builder" and "mockGeo" inside mobile app project or inside unit tests project? – Mateusz Piwowarski Nov 06 '19 at 23:46