我正在编写一个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
过于紧密联系?
答案 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);