繁体   English   中英

如何在Xamarin.Forms DependencyService中使用MOQ

[英]How do I use MOQ with Xamarin.Forms DependencyService

我正在编写一个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();

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

我该怎么做呢? 我的DepdencyService是否与Xamarin紧密耦合?

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

a)对象实例或

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

作为接口的实现。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM