如何在Xamarin.Forms DependencyService中使用MOQ

时间:2015-09-23 15:58:12

标签: c# unit-testing xamarin moq

我正在编写一个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来模拟我的接口实现,以便我的实现在运行时生成。我不想写一个模拟类,因为我的实际例子更复杂,所以意味着它不会工作。

我该怎么做呢?我的DepdencyService是否与Xamarin过于紧密联系?

1 个答案:

答案 0 :(得分:1)

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

的依赖注入框架

a)对象实例或

b)创建并返回新模拟

的方法

作为接口的实现。

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

示例

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