Task SetupWindowForTests <THandler>(IWindow window, Func <Task> runTests, IMauiContext mauiContext = null) where THandler : class, IElementHandler { mauiContext ??= MauiContext; return(InvokeOnMainThreadAsync(async() => { var applicationContext = mauiContext.MakeApplicationScope(UI.Xaml.Application.Current); var appStub = new MauiAppNewWindowStub(window); UI.Xaml.Application.Current.SetApplicationHandler(appStub, applicationContext); WWindow newWindow = null; try { ApplicationExtensions.CreatePlatformWindow(UI.Xaml.Application.Current, appStub, new Handlers.OpenWindowRequest()); newWindow = window.Handler.PlatformView as WWindow; await runTests.Invoke(); } finally { window.Handler.DisconnectHandler(); await Task.Delay(10); newWindow?.Close(); appStub.Handler.DisconnectHandler(); } })); }