use*_*er1 5 c# unit-testing moq xamarin
我正在编写一个Xamarin.Forms项目,我现在正在尝试Unit Test使用Xamarin.Forms DependencyService,如下所示:
PCL接口
public interface IGetDatabase
{
string GetDataBase()
}
Run Code Online (Sandbox Code Playgroud)
设备特定实施
[assembly: Dependency(typeof(MyProject.Droid.GetDatabaseImplementation))]
class GetDatabaseImplementation: IGetDatabase
{
public string GetDatabase()
{
return "MyDatabasePath";
}
}
Run Code Online (Sandbox Code Playgroud)
它在PCL中的调用方式如下:
DependencyService.Get<IGetDatabase>().GetDatabase();
Run Code Online (Sandbox Code Playgroud)
现在我想用unit Test它MOQ来模拟我的接口实现,以便在运行时生成我的实现。我不想编写模拟类,因为我的实际示例更复杂,因此意味着它无法工作。
我该怎么做呢?我的DepdencyService耦合太紧密了吗Xamarin?
不幸的是,您只能注册一个在当前应用程序中实现接口的类。您需要一个允许您注册的依赖注入框架
a) 一个对象实例或
b) 创建并返回新模拟的方法
作为接口的实现。
有许多不同的 C# 可用依赖注入容器。我用Mvx的是MvvmCross自带的。它允许您注册创建的模拟Moq。
例子
var myMoq = new Moq<IGetDatabase>();
Moq.Setup(x => x.GetDatabase()).Returns(() => "MyMockDatabasePath");
Mvx.RegisterSingleton<IGetDatabase>(() => myMoq.Object);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2098 次 |
| 最近记录: |