Xamarin UITest – Streamlined Back Door Calls

Here’s a mini post – Making back door calls on iOS and Android is slightly different. Here’s an extension method that works on both…

 public static class AppExtensions
 {
    public static void CallBackdoorMethod(this IApp app, string method, object argument = null)
    {
        if (app is iOSApp)
        {
if (argument == null)
{
argument = "";
}
app.Invoke($"{method}:", argument);
        }
        else
        {
            app.Invoke(method, argument);
        }
    }
}
Advertisements
Xamarin UITest – Streamlined Back Door Calls

Xamarin Forms Cross Platform Libraries and Dependency Services

This post is about how to set up cross platform libraries for Xamarin Forms, and how to implement Dependency Services in those libraries. The source code for these examples are here.

The example app is a very simple page, which shows a time string that is taken from a cross platform library, and a culture that is taken from a platform specific library via a dependency service. It looks like this…

Screen Shot 2018-02-10 at 14.02.43

Cross Platform Libraries

Adding a cross platform library is easy – simply add a Xamarin.Forms class library project to your solution, and add a project reference to your cross platform application project. You can then use classes from the library as you would expect.

Platform Libraries & Dependency Services

Things get interesting when you want to add dependency services to the library. For this you need to add an iOS class library project, and an Android class library project to your solution. You also need to add the Xamarin.Forms to both projects.

Next you have to set up the references. These are the references to add…

Sample App References: Cross Platform Library
iOS App References: Cross Platform Library, iOS Library
Android App References: Cross Platform Library, Android Library
Cross Platform Library References: -
iOS Library References: Cross Platform Library, Xamarin Forms
Android Library References: Platform Library, Xamarin Forms

Now you can define the dependency service interface in the cross platform library…

using System;

namespace SampleLibrary
{
    public interface ICultureProvider
    {
        string GetCultureString();
    }
}

And implement the interface in the platform specific libraries, here’s the iOS implementation…

using System;
using SampleLibrary.iOS;
using Xamarin.Forms;
using System.Threading;

[assembly: Dependency(typeof(CultureProvider))]
namespace SampleLibrary.iOS
{
    public class CultureProvider : ICultureProvider
    {
        public CultureProvider()
        {
        }

        public string GetCultureString()
        {
            return Thread.CurrentThread.CurrentCulture.ToString();
        }
    }
}

Remember to add the Dependency attribute! This needs to reference the implementation class, not the interface.

Now you can use DependencyService.Get to get access the service…

var cultureProvider = DependencyService.Get();
var culture = cultureProvider.GetCultureString();

For a regular dependency service defined in the application projects this would be enough. However using libraries introduces an extra foible. At compile time the application specific library might not be included in the project because there’s no reference to it in code. If this DependencyService.Get returns null. To fix this you need to add some code to the platform specific application to reference the platform specific library. This can be as simple as creating an instance of one of the classes in the library…

[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        global::Xamarin.Forms.Forms.Init();
        var foo = new SampleLibrary.iOS.CultureProvider();

        LoadApplication(new App());

        return base.FinishedLaunching(app, options);
    }
}

With the reference in place the dependency service will resolve correctly. This feels like a hack, but I haven’t found a better solution, if you have any ideas leave a comment!

Any better ideas??

Xamarin Forms Cross Platform Libraries and Dependency Services

Hyper-V and Haxm

Here’s a quick tip to make working with Hyper-V and Haxm in Windows a little easier. It’s not possible to run both at the same time which is a pain if, for example, you want to run Android emulators and Docker at the same time.

What you can do is set up a boot entry with Hyper-V turned off, then at start up you can choose to run with Hyper-V for Docker, or without to run your emulators.

To do this fire up an administrator command prompt and type

bcdedit /copy {current} /d "Hypervisor Off - Android Emulators On"

Next find and copy the identifier for the new boot entry by running

bcdedit

Then turn Hypervisor off with

bcdedit /set {newidentifier} hypervisorlaunchtype off

Restart the machine and you’ll be able to choose which one to boot 🙂

Hyper-V and Haxm

Xamarin UI Test – Testing State Management

State management, ensuring that an suspended app restarts to the same place, is one of the more challenging areas of mobile development. It’s a good idea to make sure it’s covered by your automated tests. Here’s how I managed this with Xamarin UITest…

The source code for this post is available here.

1 – Setup Tests to Run in Order

My example uses two tests, one to set the data up and one to make sure the same data is present in the restored app. The Order attribute in nunit ensures they run sequentially.

[Test, Order(1)]
public void StateTest()
{
    app = AppInitializer.StartApp(platform);
    app.Tap("Button");
    app.Tap("Button");
    app.EnterText("Text", "Some text");

    SaveAppState();
}

[Test, Order(2)]
public void StateTest2()
{
    app = AppInitializer.StartApp(platform, true);
    app.WaitForElement("Clicked 2 Times");
    app.WaitForElement(x => x.Marked("Text").Text("Some text"));
}

2 – Preserve Local Data Between Tests

In regular tests any local data will be wiped before the app is run, but here it needs to be preserved. A parameter added to the AppInitialiser controls this. This means that the local data from the first test is still in place for the second test.

public static IApp StartApp(Platform platform, bool preseveData = false)
{
    var dataMode = preseveData ? AppDataMode.DoNotClear : AppDataMode.Clear;

    if (platform == Platform.Android)
    {
        return ConfigureApp.Android
            .StartApp(dataMode);
    }
    else
    {
        return ConfigureApp.iOS
           .StartApp(dataMode);
    }
}

The documentation says that the AppDataMode attribute is only supported in test cloud, but I found it works with local tests as well.

3 – Suspend the App Programatically

When the app is stopped and restarted between tests it doesn’t get a chance to save state. To get round this the first test suspends the app programmatically. This is done via backdoor methods for each platform.

Here’s a way to suspend on iOS:

[Export("SuspendApp:")]
public void SuspendApp(NSString value)
{
    UIApplication.SharedApplication.PerformSelector(new ObjCRuntime.Selector("suspend"), null, 2.0);
}

Here’s a way to ‘suspend’ on Android (note this just triggers App.OnSleep, it doesn’t really suspend the app):

[Export("SuspendApp")]
public void SuspendApp()
{
    OnPause();
    OnStop();
}

Run the Tests!

With everything in place the last thing to do is run the tests – here’s how it looks on my machine 🙂

Xamarin UI Test – Testing State Management

Running Xamarin UITest Repl Outside of Tests

The Xamarin UITest Repl is a handy little tool for inspecting and interacting with the interface for iOS and Android apps. Normally you run it by adding app.Repl() to your test code but it’s also easy to run Repl outside of a test…

Android on Windows

To run Repl on an Android device connecting to Windows you need to know:

  • The location of the Repl executable (xut-repl.exe) – C:\Users\Username\AppData\Local\Temp\uitest\repl or similar
  • The location of the UITest dll, something like – C:\Users\Username.nuget\packages\Xamarin.UITest\2.0.10\lib\Xamarin.UITest.dll
  • The identifier for the connected device – you can get this by running adb devices

To start Repl open a command prompt and change to the executable folder. Then run xut-repl.exe android {uitestdllpath} {deviceid} after replacing the relevant values. For example:

xut-repl.exe android C:\Users\Username\.nuget\packages\Xamarin.UITest\2.0.10\lib\Xamarin.UITest.dll http://notused 15337521650191

Android and iOS on macOS

On macOS it’s a bit easier. Run Repl from a test then copy the title of the Repl window. Fire up a new terminal and enter the copied command.

Here’s an iOS example from my machine:

mono /var/folders/6l/bg1gb8v13mq5lgqgnj4_pdgw0000gn/T/uitest/repl/xut-repl.exe ios ~/Code/Trailmaker.Core/Trailmaker.Core.UITest/bin/Debug/Xamarin.UITest.dll http://127.0.0.1:37265 06C7B6BD-A7F2-436A-8BF9-A911F944A2CE true

And here’s an Android example:

mono /var/folders/6l/bg1gb8v13mq5lgqgnj4_pdgw0000gn/T/uitest/repl/xut-repl.exe android ~/Code/Trailmaker.Core/Trailmaker.Core.UITest/bin/Debug/Xamarin.UITest.dll http://127.0.0.1:60360 emulator-5554 ~Library/Developer/Xamarin/android-sdk-macosx
Running Xamarin UITest Repl Outside of Tests

Xamarin – Build on iOS from Windows Command Prompt/MSBuild

A quick post to describe how to build a Xamarin iOS project from MSBuild on a Windows machine. You still need a mac available but this approach means you can create an iOS artefact from a Windows TFS build agent.

On the command line run:

msbuild YourProject.sln /p:Configuration=AppStore;Platform=iPhone /p:ServerAddress=MacIpAddress /p:ServerUser=MacLogin /p:ServerPassword=MacPassword

When this is running keep an eye on the mac as it might pop up a message box or two on the first run.

After the script completes you should have a new IPA file in the bin\iPhone\Ad-Hoc directory of your iOS project on the Windows machine.

 

Xamarin – Build on iOS from Windows Command Prompt/MSBuild

Xamarin Forms Walkthrough UI

Here’s a walkthrough interface for use in Xamarin Forms apps. With a some work it’s easy to move beyond the default layouts and navigations patterns and make something a bit more exciting.

The video shows it in action. You can switch between pages using the buttons or by swiping. The content for the walkthrough control is defined by a list of views; it can be anything you want. The page indicators update every time you change a page.

The view provides properties to adjust the background color, back and next text, the image used for the progress indicators, and the amount of padding used for the control area.

Implementation

If you want to know how it works you can dive into the source here. In this post I’ll just run through the key parts.

The content view XAML is just a stack layout which contains two grids. The top grid expands to fill the screen and contains the child content pages when they are added. The bottom grid contains the controls to switch the page. There’s also a gesture recognizer on the whole view to pick up swipe gestures.

The key bit of code for the content view is the SetContent method. This takes a list of views and adds them into the grid. It offsets the children at intervals of a page width – so initially they extend horizontally out to right of the screen. When the page changes it animates each of the children to shift them right or left. The other thing it does is expose the configurable options.

I’ve split a lot of the logic for which pages andbuttons are displayed out into the WalkthroughController class for a couple of reasons. Firstly it’s easier to write unit tests, and secondly it nicely separates the processing and interaction logic.

That’s pretty much it – a bit of XAML and a couple of simple classes produce a nice, configurable interface 🙂

 

Xamarin Forms Walkthrough UI