【问题标题】:How do I use MOQ with Xamarin.Forms DependencyService如何将 MOQ 与 Xamarin.Forms DependencyService 一起使用
【发布时间】:2015-09-24 15:39:24
【问题描述】:

我正在写一个Xamarin.Forms 项目,我现在正在尝试Unit Test,目前我使用Xamarin.Forms DependencyService,如下所示:

PCL 接口

public interface IGetDatabase
{
   string GetDataBase()
}

设备特定实施

[assembly: Dependency(typeof(MyProject.Droid.GetDatabaseImplementation))]
class GetDatabaseImplementation: IGetDatabase
{
   public string GetDatabase()
   {
       return "MyDatabasePath";
   }
}

它在 PCL 中被这样调用:

DependencyService.Get<IGetDatabase>().GetDatabase();

现在我想unit Test 这个使用MOQ 来模拟我的接口实现,以便我的实现在运行时生成。我不想写一个模拟类,因为我的实际示例更复杂,所以这意味着它不会工作。

我该怎么做呢?我的DepdencyServiceXamarin 的耦合是否过于紧密?

【问题讨论】:

标签: c# unit-testing xamarin moq


【解决方案1】:

不幸的是,您只能在当前应用程序中注册一个实现接口的类。你需要一个允许你注册的依赖注入框架

a) 一个对象实例或

b) 创建并返回新模拟的方法

作为接口的实现。

有许多不同的 C# 依赖注入容器可用。我使用 MvvmCross 附带的Mvx。它允许您注册使用Moq 创建的模拟。

示例

var myMoq = new Moq<IGetDatabase>();
Moq.Setup(x => x.GetDatabase()).Returns(() => "MyMockDatabasePath");
Mvx.RegisterSingleton<IGetDatabase>(() => myMoq.Object);

【讨论】:

  • 谢谢。这就是我认为我必须做的,只是想知道是否有办法使用Xamarin.Forms DependencyService 来做到这一点,但看起来没有,我将不得不重构。我会用一些示例代码更新这个答案
猜你喜欢
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-19
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
相关资源
最近更新 更多