Detecting Device Idiom on Xamarin UITest
Tuesday, August 23, 2016
by asalvo
When writing UI Tests with Xamarin UITest, you may want to take a different action when testing on a tablet form factor (idiom) or phone. There is some built in support in Xamarin UITest for detecting this on the iOS side, but nothing on the Android side. The solution I came up with was to use a backdoor method to give me the information I needed.
First, let’s take a look at how we create an instance if IApp, as we will need this for both iOS and Android. I am assuming the user has a basic understanding of how Xamarin UITest works.
When setting up your Test, you will using the FluentAPI built off of ConfigureApp to create an App for either Android or iOS. This creates a platform specific instance that implements IApp.
public static IApp StartApp(Platform platform)
{
if (platform == Platform.Android)
{
return ConfigureApp.Android.DoSomeCustomAndroidConfig.StartApp();
}
return ConfigureApp.iOS..DoSomeCustomiOSConfig().StartApp()
}
In my base test class, I call StartApp and then check to see if I’m running on a phone or tablet.
[SetUp]
public void SetUp()
{
App = StartApp(Platform);
//Figure out what kind of Idiom we have.
//Use the built in support for iOS and a backdoor method for Android
var iOSApp = App as iOSApp;
if (iOSApp != null)
{
IsPhone = iOSApp.Device.IsPhone;
}
else
{
var idiom = App.Invoke("BackdoorGetIdiom");
IsPhone = idiom.Equals("Phone");
}
}
We first check to see if our App is of type iOSApp, and if it is, we’ll use the built in support in Xamarin UITest. If we are running on Android, then we’ll use the backdoor method approach, which I’ll outline next.
All I had to do was create my backdoor method and expose it from my MainActivity which is in my Xamarin Forms Android project.
[Export("BackdoorGetIdiom")]
public string BackdoorGetDeviceIdiom()
{
return Device.Idiom.ToString();
}
You may need to add a reference to the Mono.Android.Export.dll. I found this in “C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\MonoAndroid\v6.0\Mono.Android.Export.dll”. Now, all you need to do is invoke the method as shown in my [SetUp] method.
There are various rules that you must follow when writing your backdoor methods which Xamarin outlines on their backdoor documentation page. The rules differ between iOS and Android so be sure to read them carefully.