是否可以为使用Xamarin.Essentials:Geolocation API的功能创建单元测试?

时间:2019-11-06 13:24:29

标签: c# unit-testing xamarin xunit xamarin.essentials

在我的Locationer类中,我拥有使用Xamarin.Essentials:Geolocation的函数GetLocationAsync()。该功能可以正常工作,但是我想为此功能创建单元测试。

我创建了xUnitTests项目和单元测试:

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

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

在Xamarin Forms项目GetLocationAsync()中返回“纬度:46.55465,经度:15.64588,海拔:262”。

在我的单元测试中,GetLocationAsync()返回“此程序集的可移植版本未实现此功能”

是否可以在我的单元测试项目中使用Xamarin.Essentials:Geolocation?我该如何解决?

1 个答案:

答案 0 :(得分:1)

Ryan Davis已基于Xamarin创建了接口。基本信息:https://www.nuget.org/packages/Xamarin.Essentials.Interfaces/

通过这种方式,您可以在IoC容器中注册Essentials实现:

builder.Register<IGeolocation, GeolocationImplementation>();

您将能够使用Moq之类的东西来模拟界面:

var mockGeo = new Mock<IGeolocation>();
mockGeo.Setup(x => x.GetLocationAsync())
   .ReturnsAsync(() => new Location());