# BDD Unit Testing in Xamarin.Forms
# Simple Specflow to test commands and navigation with NUnit Test Runner
# Why do we need this?
The current way to do unit testing in Xamarin.Forms is via a platform runner, so your test will have to run within an ios, android, windows or mac UI environment : Running Tests in the IDE (opens new window)
Xamarin also provides awesome UI testing with the Xamarin.TestCloud (opens new window) offering, but when wanting to implement BDD dev practices, and have the ability to test ViewModels and Commands, while running cheaply on a unit test runners locally or on a build server, there is not built in way.
I developed a library that allows to use Specflow with Xamarin.Forms to easily implement your features from your Scenarios definitions up to the ViewModel, independently of any MVVM framework used for the App (such as XLabs (opens new window), MVVMCross (opens new window), Prism (opens new window))
If you are new to BDD, check Specflow (opens new window) out.
# Usage:
Add a SetupHook class to your test project, in order to add you Specflow hooks. You will need to bootstrap the test application as per below, providing the class you created above, and the your app initial viewmodel:
You will need to add a catch block to your xamarin.forms views codebehind in order to ignore xamarin.forms framework forcing you to run the app ui (something we dont want to do):
# Advanced Usage for MVVM
To add to the first example, in order to test navigation statements that occurs within the application, we need to provide the ViewModel with a hook to the Navigation. To achieve this:
- Add the package SpecFlow.Xamarin.Forms.IViewModel from nuget (opens new window) to your PCL Xamarin.Forms project
- Implement the IViewModel interface in your ViewModel. This will simply expose the Xamarin.Forms INavigation property:
public class MainViewModel : INotifyPropertyChanged, IViewModel.IViewModel { public INavigation Navigation { get; set; }
- The test framework will pick that up and manage internal navigation
- You can use any MVVM frameworks for you application (such as XLabs (opens new window), MVVMCross (opens new window), Prism (opens new window) to name a few. As long as the IViewModel interface is implemented in your ViewModel, the framework will pick it up.