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#.

Visual Studio 2019 - New Project - Android NUnit F# Template

When creating a project using the F# template Visual Studio throws an error about missing FSharp.Core and Xamarin.Android.FSharp.ResourceProvider packages.

Error Dialog

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.

Xamarin.Android.NUnitLite Framework 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.

Visual Studio 2019 - New Project - Android NUnit C# Template

Running the project will display the default NUnit test runner activity. Run the tests by tapping on “Run Tests”.

Android NUnit Test Runner Activity

The results will be displayed once complete (you may have to squint past the colour contrast issues 😎).

Android NUnit Test Runner Results

Resources

comments powered by Disqus