Skip to content

Instantly share code, notes, and snippets.

@JakeGinnivan
Created January 18, 2014 09:23
Show Gist options
  • Select an option

  • Save JakeGinnivan/8488148 to your computer and use it in GitHub Desktop.

Select an option

Save JakeGinnivan/8488148 to your computer and use it in GitHub Desktop.
Demonstrates how to host a WPF application in your test then verify visual things.
public static class TestHost
{
Application _app;
Thread _appThread;
public static void Start()
{
_appThread = new Thread(StartDispatcher);
}
public static void StartDispatcher()
{
_app = new Application { ShutdownOptions = ShutdownOptions.OnExplicitShutdown };
_app.Run();
}
public static SwitchToUIThreadAwaiter SwitchToAppThread()
{
return new SwitchToUIThreadAwaiter(_app.Dispatcher);
}
public static void Shutdown()
{
_app.InvokeShutdown();
_appThread.Join();
}
}
public class SwitchContextToUiThreadAwaiter : INotifyCompletion
{
private readonly Dispatcher _uiContext;
public SwitchContextToUiThreadAwaiter(Dispatcher uiContext)
{
_uiContext = uiContext;
}
public SwitchContextToUiThreadAwaiter GetAwaiter()
{
return this;
}
public bool IsCompleted { get { return false; } }
public void OnCompleted(Action continuation)
{
_uiContext.Invoke(s => ((Action)s)(), continuation);
}
public void GetResult() { }
}
public class AutomationTestBase
{
static AutomationTestBase()
{
TestHost.Start();
AppDomain.Unload += Unload;
}
public static Unload(..)
{
TestHost.Shutdown();
}
}
public class AutomationTests : AutomationTestBase
{
[Fact]
public async Task VerifyBrushes()
{
// Instead of this you could have TestHost.InvokeOnUIThread(()=> ...); for all interactions
// This will basically run the rest of the method on the TestHost ui thread
await TestHost.SwitchToUIThread();
var window = new MahAppsWindow();
window.Show();
// Then just use approval tests to verify it hasn't changed.
// Approval tests will render the control as an image, then do a image diff
// You can also grab the visual tree and do stuff with it
Approvals.Verify(window.FindControl("SomeControl"));
}
}
@dadhi
Copy link
Copy Markdown

dadhi commented Sep 13, 2016

Nice, thanks for useful snippet. Problem that it is not compiling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment