Windows 8商店应用程序UI(Xaml控件)单元测试

8
我一直在创建一个Windows Store应用程序,但是我在测试一个创建Grid(这是一个XAML控件)的方法时遇到了线程问题。我尝试使用NUnit和MSTest进行测试。
测试方法如下:
[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);
}  

创作者。CreateThumbnail(抛出错误的方法):
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;
}

当我运行这个测试时,它会抛出这个错误:
System.Exception: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
1个回答

11

您的控件相关代码需要在UI线程上运行。尝试使用以下方法:

[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);
}

以上代码在 MS Test 上应该可以正常运行。我不确定 NUnit 是否也适用。


非常感谢。它在MS Test中可以工作,在NUnit中无法工作。 - Marc Verdaguer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接