如何将最小起订量与 Xamarin.Forms DependencyService 一起使用
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();
现在我想 unit Test
使用 MOQ
模拟我的接口实现,以便在运行时生成我的实现。我不想写一个模拟 class 因为我的实际例子更复杂所以它不会工作。
我该怎么做?我的 DepdencyService
是否与 Xamarin
耦合得太紧?
很遗憾,您只能注册一个class,它在当前应用程序中实现了一个接口。你需要一个允许你注册的依赖注入框架
a) 对象实例或
b) 创建和 returns 新模拟的方法
作为接口的实现。
有许多不同的 C# 依赖注入容器可用。我使用 MvvmCross 附带的 Mvx
。它允许您注册使用 Moq
创建的模拟。
例子
var myMoq = new Moq<IGetDatabase>();
Moq.Setup(x => x.GetDatabase()).Returns(() => "MyMockDatabasePath");
Mvx.RegisterSingleton<IGetDatabase>(() => myMoq.Object);
我正在写一个 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
模拟我的接口实现,以便在运行时生成我的实现。我不想写一个模拟 class 因为我的实际例子更复杂所以它不会工作。
我该怎么做?我的 DepdencyService
是否与 Xamarin
耦合得太紧?
很遗憾,您只能注册一个class,它在当前应用程序中实现了一个接口。你需要一个允许你注册的依赖注入框架
a) 对象实例或
b) 创建和 returns 新模拟的方法
作为接口的实现。
有许多不同的 C# 依赖注入容器可用。我使用 MvvmCross 附带的 Mvx
。它允许您注册使用 Moq
创建的模拟。
例子
var myMoq = new Moq<IGetDatabase>();
Moq.Setup(x => x.GetDatabase()).Returns(() => "MyMockDatabasePath");
Mvx.RegisterSingleton<IGetDatabase>(() => myMoq.Object);