单元测试 Windows 8 应用商店应用 UI(Xaml 控件) [英] Unit Testing Windows 8 Store App UI (Xaml Controls)

查看:25
本文介绍了单元测试 Windows 8 应用商店应用 UI(Xaml 控件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在创建 Windows 应用商店应用程序,但在测试创建 Grid(这是一个 XAML 控件)的方法时遇到线程问题.我尝试使用 NUnit 和 MSTest 进行测试.

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.

测试方法是:

[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(抛出错误的方法):

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))

推荐答案

您的控件相关代码需要在 UI 线程上运行.试试:

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

以上内容应该适用于 MS Test.我不知道 NUnit.

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

这篇关于单元测试 Windows 8 应用商店应用 UI(Xaml 控件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆