Xamarin Android Unit Test Project
Visual Studio Android C# NUnit Template
Visual Studio 2019 doesn’t seem to ship with a C# Android unit test project template, however, there is one for F#.
When creating a project using the F# template Visual Studio throws an error about missing FSharp.Core
and Xamarin.Android.FSharp.ResourceProvider
packages.
Dismissing the dialog will still create the project, but trying to build fails with an error about a missing FSharp.Core
reference. Unfortunately, it doesn’t seem like this template has been updated in a while.
NB: I can build Android F# apps without issue.
Taking a look at MainActivity.fs
, we see it’s referencing Xamarin.Android.NUnitLite
and inheriting TestSuiteActivity
.
namespace UnitTestApp
open System.Reflection
open Android.App
open Android.OS
open Xamarin.Android.NUnitLite
[<Activity (Label = "UnitTestApp", MainLauncher = true)>]
type MainActivity () =
inherit TestSuiteActivity ()
override this.OnCreate (bundle) =
// tests can be inside the main assembly
this.AddTest (Assembly.GetExecutingAssembly ());
// or in any reference assemblies
// AddTest (typeof (Your.Library.TestClass).Assembly);
// Once you called base.OnCreate(), you cannot add more assemblies.
base.OnCreate (bundle)
Expanding the project’s references in Solution Explorer reveals that Xamarin.Android.NUnitLite
is a framework assembly reference.
Since I wanted a C# version of this project, I decided to create my own template. Starting with a blank C# app I stripped out all the extra icon/xml files, manually added the reference to NUnitLite
and updated the MainActivity
to inherit from TestSuiteActivity
. The final template is available as a zip (or GitHub), which can be imported into Visual Studio by pasting into,
%USERPROFILE%\Documents\Visual Studio 2019\Templates\ProjectTemplates
Now creating a new project in Visual Studio should surface our new C# template.
Running the project will display the default NUnit test runner activity. Run the tests by tapping on “Run Tests”.
The results will be displayed once complete (you may have to squint past the colour contrast issues 😎).