From 550551052a1105ceaccfecf82bd13b27e32b4f20 Mon Sep 17 00:00:00 2001 From: Shane Neuville Date: Wed, 7 Jun 2023 01:54:00 -0500 Subject: [PATCH] Clear window from ContextStub after it's closed --- .../DeviceTests.Shared/Stubs/ContextStub.cs | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/Core/tests/DeviceTests.Shared/Stubs/ContextStub.cs b/src/Core/tests/DeviceTests.Shared/Stubs/ContextStub.cs index 7724cd1f1108..2d4220cde2ed 100644 --- a/src/Core/tests/DeviceTests.Shared/Stubs/ContextStub.cs +++ b/src/Core/tests/DeviceTests.Shared/Stubs/ContextStub.cs @@ -54,7 +54,18 @@ public object GetService(Type serviceType) return _windowManager ??= new NavigationRootManager((UI.Xaml.Window)this.GetService(typeof(UI.Xaml.Window))); if (serviceType == typeof(UI.Xaml.Window)) - return _window ??= (_services.GetService() ?? new UI.Xaml.Window()); + { + if (_window is not null) + return _window; + + _window = (_services.GetService() ?? new UI.Xaml.Window()); + + // If a single test needs to open multiple windows then we need to clear the window + // once it's closed. This way, the next request will get a new window instead of + // trying to reuse a closed window and crashing. + _window.Closed += OnWindowClosed; + return _window; + } #endif if (serviceType == typeof(IDispatcher)) return _services.GetService(serviceType) ?? TestDispatcher.Current; @@ -62,6 +73,16 @@ public object GetService(Type serviceType) return _services.GetService(serviceType); } +#if WINDOWS + void OnWindowClosed(object sender, UI.Xaml.WindowEventArgs args) + { + if (sender is UI.Xaml.Window w) + w.Closed -= OnWindowClosed; + + _window = null; + } +#endif + public IMauiHandlersFactory Handlers => Services.GetRequiredService();