Exception thrown while trying to access UI element in WinRT Unit Testing

Next step of app is looking to automate the stuff we implemented. So that, we will not need to spend more time for ensuring the apps before we deliver.However, I was getting the error while trying to write unit test cases to check some of the UI Element’s properties. For ex, if I want to check the value of the UI element property after I made change in the ViewModel to ensure whether binding is working fine, unit test doesn’t allow to create UI controls in the background thread as it is supposed to be accessed in UI thread only.

Error message:

Test Name:    TestINRRate
Test FullName:    CurrencyConvertorTests.UnitTest1.TestINRRate
Test Source:    c:\WinRT\CurrencyConvertorTests\UnitTest1.cs : line 18
Test Outcome:    Failed
Test Duration:    0:00:00.0087226

Result Message:    Test method CurrencyConvertorTests.UnitTest1.TestINRRate threw exception:
System.Exception: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
Result StackTrace:
at Windows.UI.Xaml.Controls.Page..ctor()
at CurrencyConvertorApp.MainPage..ctor() in c:\WinRT\CurrencyConvertor\MainPage.xaml.cs:line 25
at CurrencyConvertorTests.UnitTest1.TestINRRate() in c:\WinRT\CurrencyConvertorTests\UnitTest1.cs:line 19

Solution I found it through a MSDN forum is and the below is the code block to resolve this issue.

public IAsyncAction ExecuteOnUIThread(Windows.UI.Core.DispatchedHandler action)

      {

          return Windows.ApplicationModel.Core.CoreApplication

              .MainView.CoreWindow.Dispatcher

              .RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, action);

      }



      [TestMethod]

      public async Task TestINRRate()

      {

          await ExecuteOnUIThread(() =>

           {

               MainPage page = new MainPage();

               page.Background = new SolidColorBrush(Colors.Blue);


               Assert.AreEqual(new SolidColorBrush(Colors.Blue).Color, ((SolidColorBrush)page.Background).Color);

           });


      }

This works great for me to run.

Hope this helps!!!

2 responses

  1. that’s weird, because when trying to access

    Windows.ApplicationModel.Core.CoreApplication.MainView

    I get an InvalidOperationException

    stating that “A method was called at an unexpected time.”

  2. I get the same Exception too. Is there a solution?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

<span>%d</span> bloggers like this: