单元测试的Windows 8 Store应用UI(XAML控件)(Unit Testing Wind

2019-07-17 18:41发布

我已经创建一个Windows Store应用,但我有螺纹的问题测试它创建了一个网格(这是一个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);
}  

和creator.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))

Answer 1:

您的控件相关的代码必须在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测试工作。 我不知道NUnit的。



文章来源: Unit Testing Windows 8 Store App UI (Xaml Controls)