【问题标题】:Is it possible to create unit tests for functions that use Xamarin.Essentials: Geolocation API?是否可以为使用 Xamarin.Essentials: Geolocation API 的函数创建单元测试?
【发布时间】:2023-03-06 20:56:01
【问题描述】:

在我的 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-testing xamarin xunit xamarin.essentials


【解决方案1】:

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());

【讨论】:

  • 哇,我之前没有听说过有关 IoC 容器和模拟的任何信息,所以我必须尽快阅读有关它的内容。谢谢你的帮助。我希望它会奏效。最后一个问题:我应该在移动应用项目中还是在单元测试项目中实现“builder”和“mockGeo”?
猜你喜欢
  • 2015-05-04
  • 1970-01-01
  • 2019-07-11
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 2015-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多