18th March 2017 Olivier

Cross platform unit tests with mock

Following my post on the framework SimpleStubs for UWP Unit tests, I’ll show how to do a cross platform unit test.

The idea is not to test the PCL in a “neutral” way , but test it on the 3 platforms supported by Xamarin (Android, iOS and UWP). All by reusing the same code for the tests, of course.

Creation of projects

For iOS and Android, it’s easy, simply create the basic Xamarin unit test project

CrossPlatformTests1

CrossPlatformTests2

For UWP, we will also create the basic unit test project, but we’ll turn it in unit test UWP Xamarin style.

Firstly, create the project

CrossPlatformTests3

Then, remove all references to the Visual Studio test framework :

CrossPlatformTests4

Because Xamarin use NUnit, and in order to use exactly the same source code, we’ll also use NUnit for UWP tests

Add now the Xamarin.NUnit and Xamarin Forms nugets

CrossPlatformTests5

We create now the page that contains the tests

XAML

Code behind

And, finally, we add these lines in the code-behind file of the application’s OnLaunch method, after “rootFrame.NavigationFailed += OnNavigationFailed;” :

Now let’s remove predefined tests that are in all projects.

And the projects are now ready!

Adding the tests

To begin, we will add a reference to the tested library and SimpleStubs nuget in each project:

CrossPlatformTests6

Then, add a Shared project. It is in this project that we will write tests. Like this:

Add a reference to this project to all projects unit tests, and here we are!

That is how it look like when run on each platform:

CrossPlatformTests7   CrossPlatformTests8  CrossPlatformTests9

The solution looks like this:

CrossPlatformTests10

Good tests!

The code can be found here

Mobile and Mixed Reality engineer , Arcana Studio
follow me

Leave a Reply

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