I want to Pick a file for unit testing parts of the application. how ever this is causing deadlock.
If I put breakpoint at CoreApplication
line (before Assert.IsNotNull) and start debugging by pressing F10 it wont dead lock, but I get dead lock without breakpoint.
If I mark method as async
and await result, I get InvalidOperationException
saying
A method was called at an unexpected time.
How should I fix this issue?
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);
}
Update:
if I wait for result asynchronously the application does not wait and continues the execution before I pick my file and Assert.IsNotNull(file)
fails the test.
note: I see FileOpenPicker comes for a second then test fails.
//[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);
}
This is how I call this method
[TestMethod, TestCategory("Basics")]
public async Task T02_OpenTest()
{
await T01_PickFile();
}