Unit testing Xamarin portable libraries

By Kumaran | July 22, 2019

When there is a code or feature change, it’s always very difficult to manually or even automatically test a cross-platform application. Either we don’t have enough time to test it manually or running all your automated UI tests in a variety of devices is very costly in terms of money & time. It’s a good idea to break platform-independent codes into multiple smaller portable libraries and unit test them separately. We don’t necessarily have to run UI tests to verify the changes in a portable library.

If you have to make sure that your changes are working without any issues in different platforms with unit tests, you can do that with NUnit. NUnit 3 has a unit test project template that wraps all your tests as an app and runs them when the app is launched.

Make sure that you have installed the NUnit VS Templates extension.

After that, you can create an NUnit 3 test project for the required platform. If you have to do any setup/initialization ETC. you can do that in the MainActivity (in case of Android). The same can be done with an NUnit template for iOS.

VS New Project dialog with NUnit template selection

For example, you can rename the app, using the activity label.

[Activity(Label = "Model Tests", Icon = "@drawable/icon", Theme = "@android:style/Theme.Holo.Light", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]

This app will load all tests inside the test project into the app. The app has a TestOptions property which can be used to autorun the tests on app launch & auto terminate the app once the test run is completed.

nunit.Options = new TestOptions
{
    // If True, the tests will run automatically when the app starts
    // otherwise you must run them manually.
    AutoRun = true,

    // If True, the application will terminate automatically after running the tests.
    //TerminateAfterExecution = true,

    // Information about the tcp listener host and port.
    //TcpWriterParameters = new TcpWriterInfo("", 13000),

    // Creates a NUnit Xml result file on the host file system using PCLStorage library.
    // CreateXmlResultFile = true,

    // Choose a different path for the xml result file
    // ResultFilePath = Path.Combine(Environment.ExternalStorageDirectory.Path, Environment.DirectoryDownloads, "Nunit", "Results.xml")
};

LoadApplication(nunit);

Test details give the same information which we get from a regular NUnit test run. The only drawback is, we can’t run a specific test individually.

NUnit Test results summary page Test result details page

NOTE: This is useful only if you have to test your portable library on all platforms it supports. For example, a portable library that uses SQLite must be tested on each platform separately.

Share on: