0

我想为应用程序的单元测试部分选择一个文件。这如何导致僵局。

如果我CoreApplication在行(Assert.IsNotNull 之前)放置断点并按 F10 开始调试,它不会死锁,但我会在没有断点的情况下得到死锁。

如果我将方法标记为async并等待结果,我会InvalidOperationException

在意外的时间调用了一个方法。

我应该如何解决这个问题?

private StorageFile file;    

//[TestMethod, TestCategory("Basics")]
public void T01_PickFile()
{
    // initialize picker
    var picker = new FileOpenPicker
    {
        SuggestedStartLocation = PickerLocationId.Desktop,
        ViewMode = PickerViewMode.List
    };
    picker.FileTypeFilter.Add(".txt");

    // grant access and pick file
    // deadlock if there is no breakpoint
    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        file = picker.PickSingleFileAsync().GetAwaiter().GetResult();
    }).GetAwaiter().GetResult();

    Assert.IsNotNull(file);
}

更新:

如果我异步等待结果,则应用程序不会等待并在我选择文件并Assert.IsNotNull(file)通过测试之前继续执行。

注意:我看到 FileOpenPicker 出现了一秒钟然后测试失败。

//[TestMethod, TestCategory("Basics")]
public async Task T01_PickFile()
{
    // initialize picker
    var picker = new FileOpenPicker
    {
        SuggestedStartLocation = PickerLocationId.Desktop,
        ViewMode = PickerViewMode.List
    };
    picker.FileTypeFilter.Add(".mid");

    // grant access and pick file
    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
    {
        file = await picker.PickSingleFileAsync();
    });

    Assert.IsNotNull(file);
}

我就是这样称呼这个方法的

[TestMethod, TestCategory("Basics")]
public async Task T02_OpenTest()
{
    await T01_PickFile();
}
4

0 回答 0