Invalid cross-thread access in Windows phone unit test

If your unit tests try to do stuff that needs the UI thread, you will be greeted by  visual studio with this message:


Test method threw exception: 
System.UnauthorizedAccessException: Invalid cross-thread access.

This exception occurs because you try to do things that need the UI thread on a thread that is different from the UI thread.

The solution is to dispatch your code to run on the UI thread.

It can be done with the help of this class:


using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace Thumbmunkeys.Common.WindowsPhone.Test
{
    public class UITestHelper
    {
        public static async Task RunOnUiThread(Func<Task> a)
        {
            var autoResetEvent = new AutoResetEvent(false);
            Exception exception = null;

            Deployment.Current.Dispatcher.BeginInvoke(async () =>
            {
                try
                {
                    await a();
                }
                catch (Exception ex)
                {
                    exception = ex;
                }
                finally
                {
                    autoResetEvent.Set();
                }
            });

            autoResetEvent.WaitOne();

            if (exception != null)
                throw exception;
        }
    }
}

This is how you would invoke it:


[TestMethod]
public async Task Test()
{
    await UiTestHelper.RunOnUiThread(async () =>
    {
          // Test code here....
    });
}