[英]How do I use MOQ with Xamarin.Forms DependencyService
I am writing a Xamarin.Forms
project which I am now trying to Unit Test
currently I use the Xamarin.Forms DependencyService like so: 我正在编写一个Xamarin.Forms
项目,我现在尝试Unit Test
目前我使用Xamarin.Forms DependencyService,如下所示:
PCL Interface PCL接口
public interface IGetDatabase
{
string GetDataBase()
}
Device specific Implementation 设备特定实施
[assembly: Dependency(typeof(MyProject.Droid.GetDatabaseImplementation))]
class GetDatabaseImplementation: IGetDatabase
{
public string GetDatabase()
{
return "MyDatabasePath";
}
}
And it is called in the PCL like so: 在PCL中调用它是这样的:
DependencyService.Get<IGetDatabase>().GetDatabase();
Now I would like to unit Test
this using MOQ
to Mock my interface implementation so that my implementations are generated at runtime. 现在我想使用MOQ
对我的接口实现进行unit Test
以便我的实现在运行时生成。 I don't want to write a mock class as my actual example is more complicated so means it wont work. 我不想写一个模拟类,因为我的实际例子更复杂,所以意味着它不会工作。
How would I go about doing this? 我该怎么做呢? Is my DepdencyService
too tightly coupled to Xamarin
? 我的DepdencyService
是否与Xamarin
紧密耦合?
Unfortunately you can only register a class that implements an interface in the current application. 遗憾的是,您只能在当前应用程序中注册实现接口的类。 You need a dependency injection framework that allows you to register 您需要一个允许您注册的依赖注入框架
a) an object instance or a)对象实例或
b) a method that creates and returns a new mock b)创建并返回新模拟的方法
as the implementation for an interface. 作为接口的实现。
There are many different dependency injection containers for C# available. C#有许多不同的依赖注入容器可用。 I use Mvx
which comes with MvvmCross. 我使用Mvx
和MvvmCross一起使用。 It allows you to register mocks created wit Moq
. 它允许您注册Moq
创建的Moq
。
Example 例
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.