Gordonium
Gordonium

Reputation: 3487

Why does this unit test throw an "Element not found" exception?

I have created a very basic unit test for my C# project. The application is a thick client based on UWP so I am using Universal unit tests. I run the test and it fails with a System.Exception: Element not found message. It also says

GetForCurrentView must be called on a thread that is associated with a CoreWindow

I've added the main project as a reference to the test project.

Here is a minimum working example:

namespace MyProjectTests
{
    [TestClass]
    public class ExampleObjectTest
    {
        private ExampleObject exampleObject;

        [TestInitialize]
        public void Setup()
        {
            exampleObject = new ExampleObject();
        }

        [TestMethod]
        public void RequestParametersIsNotNullTest()
        {
            Dictionary<string, string> parameters = exampleObject.MethodThatReturnsDictionary();
            Assert.IsNotNull(parameters);
        }
    }
}

StackTrace:

DisplayInformation.GetForCurrentView()
ExampleObject.MethodThatReturnsDictionary()
ExampleObjectTest.RequestParametersIsNotNullTest()

This method does not return null but the test still fails. Is there further setup required in order to ensure this test passes?

Upvotes: 3

Views: 1633

Answers (1)

Stam
Stam

Reputation: 2490

You have to create a static method inside a helper class to execute the given code on the UI thread.

ThreadHelper.cs :

    public static class ThreadHelper
    {

        public static IAsyncAction ExecuteOnUIThread(Windows.UI.Core.DispatchedHandler action)
        {
            return Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, action);
        }
    }

and then inside your TestMethod:

        [TestMethod]
        public async Task RequestParametersIsNotNullTest()
        {
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            await ThreadHelper.ExecuteOnUIThread(() =>
            {
               exampleObject.MethodThatReturnsDictionary();
            });
            Assert.IsNotNull(parameters);
        }

Do not forget to replace void with async Task.

Upvotes: 3

Related Questions