Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 896
Gordonium Avatar asked Nov 18 '25 07:11

Gordonium


1 Answers

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.

like image 126
Stam Avatar answered Nov 20 '25 19:11

Stam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!