I have an MVVM project in Xamarin.Forms and I'm trying to write some unit tests to cover it. In the ViewModel I have this code to open a new page:
//1st (working) navigation
public ICommand WardSelectedCommand => new Command(async () => await WardSelected());
private async Task WardSelected()
{
var vm = _dependencyResolver.GetDependency<WardDetailViewModel>();
var page = new WardDetailPage(vm);
await _pageNavigationService.PushModalAsync(page);
}
//2nd (broken in unit tests) navigation
public ICommand PatientSelectedCommand => new Command(async() => await PatientSelected());
private async Task PatientSelected()
{
var vm = _dependencyResolver.GetDependency<PatientPegViewModel>();
var page = new PatientPegPage(vm);
await _pageNavigationService.PushModalAsync(page);
}
When the page in the method is a ContentPage, everything is fine and the unit tests run. When the page is a TabbedPage instead though I get the below error in the test runner, failing on the 2nd line in the 2nd example while running the constructor. There is no difference in the xaml or xaml.cs files other than the page inheriting from the TabbedPage, they are just 2 blank template pages generated in vs with no content at all. I even tried turning the PatientPegPage
into a ContentPage
and the unit test ran without errors, but when changing it back to TabbedPage
the error came back.
The active test run was aborted. Reason: Test host process crashed : Unhandled exception. System.InvalidOperationException: You MUST call Xamarin.Forms.Init(); prior to using it.
I have tried adding the line of code suggested in the error message Xamarin.Forms.Init()
but a) that seems like bad practice in a unit test and b) It doesn't compile, with the message The type or namespace 'Init' does not exist in the namespace 'Xamarin.Forms' (are you missing an assembly reference?)