2013-01-02 52 views
7

我一直在創建一個Windows應用商店應用程序,但我有線程問題測試創建一個網格(這是一個XAML控件)的方法。 我試過使用NUnit和MSTest進行測試。單元測試Windows 8商店應用程序用戶界面(Xaml控件)

的測試方法是:

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

回答

9

您的控件相關代碼需要在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。

+0

非常感謝。 它適用於MS Test。在NUnit中它不起作用。 –

相關問題