When running your UI tests, locally or in Xamarin Test Cloud, you sometimes want to execute code in your app from your tests. You might for instance want to setup some mock implementations instead of making actual API calls, or you might want to trigger some OS specific code from your tests. In these scenario’s backdoors come in handy!
Backdoors itself are not very complex, but it opens up a lot of possibilities with UI tests. In the past I used backdoors to:
- Setup authentication for tests
- Create a specific state in your app to run your tests in.
- Set mock implementations from my UI tests.
- Trigger deeplink
And I can think of a lot more useful scenario’s. You can create a backdoor with the following code:
iOS
In your AppDelegate class you need to create an method that returns NSString, is public, is annotated with Export attribute and takes an NSString as parameter. For example:
public class AppDelegate : UIApplicationDelegate { [Export("myBackdoorMethod:")] // notice the colon at the end of the method name public NSString MyBackdoorMethod(NSString value) { // In through the backdoor - do some work. } }
Android
On Android you need to create a method in your MainActivity that is public, returns string/void, is annotated with Export attribute and takes an string/int/bool as parameter:
public class MainActivity : Activity { [Export("MyBackdoorMethod")] public void MyBackdoorMethod(string value) { // In through the backdoor - do some work. } }
Invoking the backdoor from your UI tests:
if (app is Xamarin.UITest.iOS.iOSApp) { app.Invoke("myBackdoorMethod:", "exampleString"); } else { app.Invoke("MyBackdoorMethod", "exampleString"); }
Note: The signature of the backdoor methods is very important as the Backdoors – Xamarin docs mention.
If you want to switch out your actual implementations for mocks, the use of compiler flags (combined with build configurations) might be more suited. You can read more on this over here.
Related links:
- Backdoors – Xamarin documentation: https://developer.xamarin.com/guides/testcloud/uitest/working-with/backdoors/
- IApp.Invoke – Xamarin documentation: https://developer.xamarin.com/api/member/Xamarin.UITest.IApp.Invoke/p/System.String/System.Object/