Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions docs/UITesting-Guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,62 @@ dotnet build ./src/Provisioning/Provisioning.csproj -t:ProvisionAppium -p:SkipAp
- Xcode with command-line tools installed
- iOS Simulator configured

## Android Shell Handler and Renderer Lanes

The main Android UI-test stage runs `Shell1` and `Shell2` as separate matrix jobs
using Shell Handler. The separate `android_ui_tests_shell_renderer` stage runs the
same two shards as separate matrix jobs using Shell Renderer. Each renderer job
uses its shard category as the test filter, so the entire Shell suite is not
repeated in each job. Both stages depend on `build_ui_tests_coreclr` and download
the same `ui-tests-samples-coreclr` artifact; there is no separate app build or
MSBuild property for Shell selection.

Android Mono is not supported when targeting .NET 11 or later. Enabling
`UseMonoRuntime=true` for `net11.0-android` fails with `NETSDK1242`, so there is no
Android Mono build or test lane on this branch. Mono coverage requires a separate
.NET 10-targeted app build; the shared templates' `Mono` option does not make a
.NET 11 Android app compatible with Mono.

The renderer lane sets `testConfigurationArgs: "ShellRenderer"`. The Android Cake
runner forwards this through `TEST_CONFIGURATION_ARGS` to Appium, which passes it
as an activity intent extra on startup and relaunch. `MainActivity` reads the
setting before creating the window, and the Shell handler factory in
`MauiProgram.cs` selects the renderer when each Shell is created. Without the
setting, it selects Shell Handler. The selected implementation is logged to logcat
under the `MauiUITests` tag.

To run the renderer configuration locally with an already-built HostApp:

```bash
./build.sh -Script eng/devices/android.cake --target=uitest \
--test-filter="TestCategory=Shell" --TEST_CONFIGURATION_ARGS="ShellRenderer"
```

The `Shell` umbrella category still selects the complete suite locally. Use
`TestCategory=Shell1` or `TestCategory=Shell2` to run an individual shard, matching
the CI jobs.

Omit `--TEST_CONFIGURATION_ARGS` (and unset that environment variable) to run the
default Shell Handler configuration. Both configurations use the existing Android
snapshot baselines.

For a known renderer-only failure, call the shared test extension at the start of
the affected test, including the tracking issue in the reason:

```csharp
this.IgnoreOnAndroidShellRenderer(
"Fails with Android ShellRenderer: https://github.com/dotnet/maui/issues/39461");
```

This reports the test as ignored only in the Android Shell Renderer configuration.
The default Handler lane and other platforms continue running the test.

For a known Handler-only failure, use
`this.IgnoreOnAndroidShellHandler("Reason and tracking issue URL")` instead. This
skips only the Android Handler configuration, leaving Renderer coverage enabled.
Both helpers leave other platforms unaffected. Use only the relevant helper for
each affected test and remove the call when its issue is fixed.

## Creating a UI Test

### Step 1: Create the HostApp Page
Expand Down
4 changes: 4 additions & 0 deletions eng/devices/android.cake
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,10 @@ void ExecutePrepareUITests(string project, string app, string appPackageName, st
void ExecuteUITests(string project, string app, string appPackageName, string device, string resultsDir, string binDir, string config, string tfm, string rid, string ver, string toolPath, string instrumentation)
{
string platform = "android";
var TEST_CONFIGURATION_ARGS = Argument("TEST_CONFIGURATION_ARGS", EnvironmentVariable("TEST_CONFIGURATION_ARGS") ?? "");
Information("TEST_CONFIGURATION_ARGS {0}", TEST_CONFIGURATION_ARGS);
SetEnvironmentVariable("TEST_CONFIGURATION_ARGS", TEST_CONFIGURATION_ARGS);

Information("Build UITests project {0}", project);

var name = System.IO.Path.GetFileNameWithoutExtension(project);
Expand Down
46 changes: 46 additions & 0 deletions eng/pipelines/common/ui-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,52 @@ stages:
platform: 'Android'
artifactName: 'uitest-snapshot-results-android-$(System.StageName)-$(System.JobName)-$(System.JobAttempt)'

- stage: android_ui_tests_shell_renderer
displayName: Android UITests Shell Renderer
dependsOn: build_ui_tests_coreclr
jobs:
- ${{ each project in parameters.projects }}:
- ${{ if ne(project.android, '') }}:
- ${{ each api in parameters.androidApiLevels }}:
- ${{ if not(containsValue(project.androidApiLevelsExclude, api)) }}:
- job: shell_renderer_android_ui_tests_${{ project.name }}_${{ api }}
strategy:
matrix:
Shell1:
CATEGORYGROUP: Shell1
Shell2:
CATEGORYGROUP: Shell2
timeoutInMinutes: 240
workspace:
clean: all
displayName: ${{ coalesce(project.desc, project.name) }} Shell Renderer (API ${{ api }})
pool: ${{ parameters.androidLinuxPool }}
variables:
APPIUM_HOME: $(System.DefaultWorkingDirectory)/.appium/
steps:
- template: ui-tests-steps.yml
parameters:
platform: android
version: ${{ api }}
path: ${{ project.android }}
app: ${{ project.app }}
${{ if eq(api, 27) }}:
device: android-emulator-32_${{ api }}
${{ if not(eq(api, 27)) }}:
device: android-emulator-64_${{ api }}
provisionatorChannel: ${{ parameters.provisionatorChannel }}
agentPoolAccessToken: ${{ parameters.agentPoolAccessToken }}
testFilter: $(CATEGORYGROUP)
testConfigurationArgs: "ShellRenderer"
headless: ${{ parameters.headless }}
skipProvisioning: ${{ parameters.skipProvisioning }}
runtimeVariant: "CoreCLR"

- template: ui-tests-collect-snapshot-diffs.yml
parameters:
platform: 'Android Shell Renderer'
artifactName: 'uitest-snapshot-results-android-shell-renderer-$(System.StageName)-$(System.JobName)-$(System.JobAttempt)'

- stage: android_ui_tests_material3
displayName: Android UITests Material3
dependsOn: build_ui_tests_material3
Expand Down
9 changes: 9 additions & 0 deletions src/Controls/tests/TestCases.HostApp/MauiProgram.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,15 @@ public static MauiApp CreateMauiApp()
handlers.AddHandler(typeof(Issue34310NativeHostView), typeof(Issue34310NativeHostViewHandler));
#endif
#if ANDROID
// The application is built before MainActivity receives the lane's launch intent.
handlers.AddHandler<Shell>(static _ =>
{
IElementHandler handler = Platform.MainActivity.UseShellRenderer
? new Microsoft.Maui.Controls.Handlers.Compatibility.ShellRenderer()
: new Microsoft.Maui.Controls.Handlers.ShellHandler();
Android.Util.Log.Info("MauiUITests", $"Using {handler.GetType().Name}");
return handler;
});
handlers.AddHandler(typeof(Issue7814TouchClaimView), typeof(Issue7814TouchClaimViewHandler));
#endif
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,12 @@ namespace Maui.Controls.Sample.Platform
[Register("com.microsoft.maui.uitests.MainActivity")]
public class MainActivity : MauiAppCompatActivity
{
internal static bool UseShellRenderer { get; private set; }

protected override void OnCreate(Android.OS.Bundle savedInstanceState)
{
UseShellRenderer = string.Equals(Intent?.GetStringExtra("TEST_CONFIGURATION_ARGS"), "ShellRenderer", StringComparison.OrdinalIgnoreCase);
base.OnCreate(savedInstanceState);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ public void VerifyShellFlyoutContentAlignedInRTL()
[ShardedTestCategory(UITestCategories.Shell, shard: 2)]
public void VerifyShellMenuItemsAlignedInRTL()
{
this.IgnoreOnAndroidShellRenderer("Fails with Android ShellRenderer: https://github.com/dotnet/maui/issues/39461");

App.WaitForElement("homePageLabel");
App.Tap("FlyoutLockedButton");
App.WaitForElement("MenuItem 1");
Expand Down
26 changes: 26 additions & 0 deletions src/Controls/tests/TestCases.Shared.Tests/UtilExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,32 @@ public static class UtilExtensions
{
const string goToTestButtonId = "GoToTestButton";

/// <summary>
/// Ignores the current test only when running in the Android Shell Renderer configuration.
/// </summary>
public static void IgnoreOnAndroidShellRenderer(this UITestContextBase testBase, string reason)
{
if (testBase.Device == TestDevice.Android && string.Equals(
Environment.GetEnvironmentVariable("TEST_CONFIGURATION_ARGS"),
"ShellRenderer", StringComparison.OrdinalIgnoreCase))
{
Assert.Ignore(reason);
}
}

/// <summary>
/// Ignores the current test only when running in the Android Shell Handler configuration.
/// </summary>
public static void IgnoreOnAndroidShellHandler(this UITestContextBase testBase, string reason)
{
if (testBase.Device == TestDevice.Android && !string.Equals(
Environment.GetEnvironmentVariable("TEST_CONFIGURATION_ARGS"),
"ShellRenderer", StringComparison.OrdinalIgnoreCase))
{
Assert.Ignore(reason);
}
}

public static void Back(this UITestContextBase testBase)
{
if (testBase.Device == TestDevice.Android)
Expand Down
25 changes: 21 additions & 4 deletions src/TestUtils/src/UITest.Appium/Actions/AppiumLifecycleActions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ CommandResponse LaunchApp(IDictionary<string, object> parameters)
{ "environment", args },
});
}
else if (_app is AppiumAndroidApp androidApp)
{
androidApp.ActivateApp();
}
else
{
_app.Driver.ActivateApp(_app.GetAppId());
Expand All @@ -115,7 +119,11 @@ CommandResponse ForegroundApp(IDictionary<string, object> parameters)
}
else
{
_app.Driver.ActivateApp(_app.GetAppId());
if (_app is AppiumAndroidApp androidApp)
androidApp.ActivateApp();
else
_app.Driver.ActivateApp(_app.GetAppId());

// Give it time for the animation to settle, otherwise there's a risk
// of picking wrong elements coordinates and `Tap`s will fail silently.
Thread.Sleep(100);
Expand Down Expand Up @@ -349,12 +357,21 @@ CommandResponse RecoverFromCrash(IDictionary<string, object> parameters)
// case the driver session is wedged from the crash.
try
{
_app.Driver.ActivateApp(appId);
LaunchApp(parameters);
}
catch (Exception ex)
{
Debug.WriteLine($">>>>> RecoverFromCrash ActivateApp failed, falling back to monkey: {ex.Message}");
RunAdb("shell", "monkey", "-p", appId, "-c", "android.intent.category.LAUNCHER", "1");
Debug.WriteLine($">>>>> RecoverFromCrash launch failed, falling back to adb: {ex.Message}");
var args = _app.Config.GetProperty<Dictionary<string, string>>("TestConfigurationArgs");
if (args is not null && args.TryGetValue("TEST_CONFIGURATION_ARGS", out var configurationArgs) && !string.IsNullOrEmpty(configurationArgs))
{
RunAdb("shell", "am", "start", "-W", "-n", $"{appId}/{appId}.MainActivity",
"--es", "TEST_CONFIGURATION_ARGS", configurationArgs);
}
else
{
RunAdb("shell", "monkey", "-p", appId, "-c", "android.intent.category.LAUNCHER", "1");
}
}

return CommandResponse.SuccessEmptyResponse;
Expand Down
34 changes: 32 additions & 2 deletions src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ public static AppiumAndroidApp CreateAndroidApp(Uri remoteAddress, IConfig confi
{
var device = config.GetProperty<string>("EmulatorDeviceName");
var apkPath = config.GetProperty<string>("AppPath");
var pkgName = config.GetProperty<string>("AppId");
var outDir = config.GetProperty<string>("ReportDirectory");
var enableDebugPopup = config.GetProperty<bool>("EnableDebugPopup");
var avdForce = config.GetProperty<bool>("AvdForceInstall");
Expand All @@ -39,10 +38,38 @@ public static AppiumAndroidApp CreateAndroidApp(Uri remoteAddress, IConfig confi
//// TODO: Check for installed package first?
//AndroidEmulator.InstallPackage(apkPath, pkgName, outDir);
var androidApp = new AppiumAndroidApp(remoteAddress, config);
androidApp.Driver.ActivateApp(pkgName);
androidApp.ActivateApp(forceRestart: true);
return androidApp;
}

internal void ActivateApp(bool forceRestart = false)
{
var appId = this.GetAppId();
var args = GetTestConfigurationArgs(Config);
if (string.IsNullOrEmpty(args))
{
Driver.ActivateApp(appId);
return;
}

Driver.ExecuteScript("mobile: startActivity", new Dictionary<string, object>
{
{ "component", $"{appId}/{appId}.MainActivity" },
{ "action", "android.intent.action.MAIN" },
{ "categories", new[] { "android.intent.category.LAUNCHER" } },
{ "flags", "0x10200000" },
{ "extras", new[] { new[] { "s", "TEST_CONFIGURATION_ARGS", args } } },
{ "wait", true },
{ "stop", forceRestart },
});
}

static string? GetTestConfigurationArgs(IConfig config)
{
var args = config.GetProperty<Dictionary<string, string>>("TestConfigurationArgs");
return args is not null && args.TryGetValue("TEST_CONFIGURATION_ARGS", out var value) ? value : null;
}

public override IUIElementQueryable Query => new AppiumAndroidQueryable(this);

public override ApplicationState AppState
Expand Down Expand Up @@ -89,6 +116,9 @@ private static AppiumOptions GetOptions(IConfig config)

SetGeneralAppiumOptions(config, options);

if (!string.IsNullOrEmpty(GetTestConfigurationArgs(config)))
options.AddAdditionalAppiumOption("autoLaunch", false);

if (!string.IsNullOrWhiteSpace(appId))
{
options.AddAdditionalAppiumOption(MobileCapabilityType.NoReset, "true");
Expand Down
Loading