首页 > 解决方案 > 是否可以为使用 Xamarin.Essentials: Geolocation API 的函数创建单元测试?

问题描述

在我的Locationer课堂上,我有GetLocationAsync()使用 Xamarin.Essentials: Geolocation 的函数。此功能工作正常,但我想为此功能创建单元测试。

我创建了 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:地理位置?我该如何解决?

标签: c#unit-testingxamarinxunitxamarin.essentials

解决方案


Ryan Davis 创建了基于 Xamarin.Essentials 的接口: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());

推荐阅读