[英]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.