Unit Testing Windows 8 Store App UI (Xaml Controls)

时光总嘲笑我的痴心妄想 提交于 2019-12-19 06:03:12

问题


I've been creating a Windows Store App but I have thread problems testing a method which creates a Grid (Which is a XAML Control). I've tried to test using NUnit and MSTest.

The test method is:

[TestMethod]
public void CreateThumbnail_EmptyLayout_ReturnsEmptyGrid()
{
    Layout l = new Layout();
    ThumbnailCreator creator = new ThumbnailCreator();
    Grid grid = creator.CreateThumbnail(l, 192, 120);

    int count = grid.Children.Count;
    Assert.AreEqual(count, 0);
}  

And the creator.CreateThumbnail (The method which throws the error):

public Grid CreateThumbnail(Layout l, double totalWidth, double totalHeight)
{
     Grid newGrid = new Grid();
     newGrid.Width = totalWidth;
     newGrid.Height = totalHeight;

     SolidColorBrush backGroundBrush = new SolidColorBrush(BackgroundColor);
     newGrid.Background = backGroundBrush;

     newGrid.Tag = l;            
     return newGrid;
}

When I run this test it throws this error:

System.Exception: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))

回答1:


Your controls related code needs to be run on a UI thread. Try:

[TestMethod]
async public Task CreateThumbnail_EmptyLayout_ReturnsEmptyGrid()
{
    int count = 0;
    await ExecuteOnUIThread(() =>
    {
        Layout l = new Layout();
        ThumbnailCreator creator = new ThumbnailCreator();
        Grid grid = creator.CreateThumbnail(l, 192, 120);
        count = grid.Children.Count;
    });

    Assert.AreEqual(count, 0);
}

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

The above should work on MS Test. I don't know about NUnit.



来源:https://stackoverflow.com/questions/14118956/unit-testing-windows-8-store-app-ui-xaml-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!