5

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?

JKennedy
  • 18,150
  • 17
  • 114
  • 198

1 Answers1

3

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);
JKennedy
  • 18,150
  • 17
  • 114
  • 198
Wosi
  • 41,986
  • 17
  • 75
  • 82
  • 1
    Thank you. This is what I thought I had to do, just wondered if there was a way to do it with `Xamarin.Forms DependencyService` but it looks like there isn't and I'm going to have to refactor. I'll update this answer with some example code – JKennedy Sep 24 '15 at 07:37