DevelopmentXamarin

Unit testing Xamarin Forms. Overcome “You MUST call Xamarin.Forms.Init()” problem.

 

Introduction.

When doing Xamarin Forms unit testing, you will sooner or later hit at “You MUST call Xamarin.Forms.Init()” problem. In other words, this message simply tells that Xamarin Forms must be initialized in order to perform the test. In this post I will describe one way how I handled this issue!

Demo app.

To put the problem into the context, I prepared simple Xamarin Forms App to demonstrate how easy can developer crush into “You MUST call Xamarin.Forms.Init() “ problem.

That is to say, my demo application is very simple – Xamarin Forms application with one simple page. As I normally do, I follow Model-View-ViewModel (MVVM) pattern, because this approach has some benefits over “classical – code behind – approach”. MVVM with Dependency Injection enables to write very flexible and testable code.

Source code is available here: https://github.com/josipx/Jenx.Xamarin.UnitTestExample. I omitted iOS version of the app for code and solution brevity.

MainPage View
MainPage ViewModel

To be more plastic, here is the Android screenshot of my testing app. App has input field and three buttons. First button redirects to my web site, other two bind some text to input field. If you check the code, you can see that two buttons uses Device utility class.

Unit tests.

For unit tests I used super-doper unit testing framework xUnit!

Simple unit test without Device utility class.

Unit test runner shows everything is just fine.

Unit test with Device utility class.

BAM, unit test runner shows failure.

So, before executing this unit test, Xamarin Forms must be initialized. Let’s try to fix this.

Solution: Mocking Device.PlatformServices.

After short investigation, I found out that Device.PlatformServices property must be set. This property implements Xamarin.Forms.Internals.IPlatformServices. Thus, I tried to mock this functionality with really awesome mocking library FakeItEasy. I simply extended unit test class by mocking this functionality inside constructor (xUnit way of unit test class initialization), e.g.

As a result, I got my unit tests positive!

Example of unit testing ICommand which calls Device APIs.

Now, with unit test working, I included additional unit test. I tried to put a check if underlying Device utility gets correct url to navigate to from my command.

Conclusion.

In short, if you extend your Xamarin Forms with unit tests, you will surely hit “You MUST call Xamarin.Forms.Init()” exception (technically speaking System.InvalidOperationException).

This blog post shows one way how to handle this situation by mocking Device.PlatformServices.

How you handled this situation?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.