I am writing a Xamarin.Forms
project which I am now trying to Unit Test
currently I use the Xamarin.Forms DependencyService like so:
PCL Interface
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:
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. 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
?
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
b) a method that creates and returns a new mock
as the implementation for an interface.
There are many different dependency injection containers for C# available. I use Mvx
which comes with MvvmCross. It allows you to register mocks created wit Moq
.
Example
var myMoq = new Moq<IGetDatabase>();
Moq.Setup(x => x.GetDatabase()).Returns(() => "MyMockDatabasePath");
Mvx.RegisterSingleton<IGetDatabase>(() => myMoq.Object);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.