Xamarin.UITest Backdoor with Splash Screen

791 views Asked by At

I have an application that I'm attempting to put Xamarin UI Tests on. I need to Backdoor the app to bypass my login process. My Backdoor method fires just fine.

[Activity(Label = "AppName", Icon = "@drawable/icon", Theme = "@style/Theme.Splash", MainLauncher = true, NoHistory = true)]
public class SplashActivity : Activity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        StartActivity(typeof(MainActivity));
    }

    [Java.Interop.Export("BackDoor")] 
    public void BackDoor()
    {
        var myActivity = {Magic code to get reference to the the instance of MainActivity goes here} 


    }

}

However its firing in my Splash screen and I need it get a reference to my actual MainActivity not my SplashActivity. How do I get a reference to the MainActivity in my BackDoor method?

Xamarin Backdoor Docs: https://developer.xamarin.com/recipes/testcloud/start-activity-with-backdoor/ https://developer.xamarin.com/guides/testcloud/uitest/working-with/backdoors/

2

There are 2 answers

4
Brandon Minnick On BEST ANSWER

How To Retrieve Current Activity

To retrieve the MainActivity, you can use @JamesMontemagno's CurrentActivityPlugin.

Add the Current Activity NuGet Package into your Xamarin.Android project, and then, in your Xamarin.Android Project, you can use the following line of code to retrieve the current activity and check that it is the MainActivity.

Activity currentActivity = Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity as MainActivity;

if (!(currentActivity is MainActivity))
    throw new System.Exception("Current Activity is not MainActivity");

This plugin is open-sourced on GitHub.

2
jgoldberger - MSFT On

According to the guide for a backdoor method for Android, it can not return object type, only string, Java.Lang.String, or void. See: https://developer.xamarin.com/guides/testcloud/uitest/working-with/backdoors/

Don't you want to start the next Activity from the backdoor as in the guide? If so, just follow the guide you linked more closely.

Also, just double checked and returning object from the BackDoor method fails on build with a NullReferenceException. However, for "{Magic code to get reference to the the instance of MainActivity goes here}" you can do:

ActivityManager am = (ActivityManager)this.GetSystemService(Context.ActivityService);
var myActivity = am.GetRunningTasks(1)[0].TopActivity;

the myActivity will be a reference to the top most activity, but you can't return it from the BackDoor method anyway. You can return a string description of course. I do not know why you need a reference to the activity in your test code anyway as there is not much you can do with it in the test code.