Unit Testing Windows 8 Store App UI (Xaml Controls)(单元测试 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 控件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:单元测试 Windows 8 应用商店应用 UI(Xaml 控件)
				
        
 
            
        - C#MongoDB使用Builders查找派生对象 2022-09-04
 - 如何用自己压缩一个 IEnumerable 2022-01-01
 - 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
 - WebMatrix WebSecurity PasswordSalt 2022-01-01
 - 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
 - MoreLinq maxBy vs LINQ max + where 2022-01-01
 - 输入按键事件处理程序 2022-01-01
 - Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
 - C# 中多线程网络服务器的模式 2022-01-01
 - 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
 
						
						
						
						
						
				
				
				
				