我具有通过调用Task.Run()从存储库获取数据并使用结果填充ObservableCollection的功能。对于WPF MVVM项目本身,它运行良好。但是,当我从单元测试中运行它时,它会抛出错误“该类型的CollectionView不支持从不同于调度线程的线程对其SourceCollection进行更改。
我不确定单元测试用例有什么问题。
非常感谢您的帮助。
这是C#函数:
public async Task RefreshItems()
{
try
{
Items.Clear(); // the Items is an ObservableCollection
var data = await Task.Run(() => _connectionContext.Repository.SearchFolders("default", SearchTerm));
// this line throws exception for unit test
Items.AddRange(data.Select(x => Mapper.Map<LoanFolderResource, LoanFolderModel>(x)));
}
catch (Exception e)
{
Log.Error("Failed loading databases and/or users for connection", e);
}
}
这是测试用例:
public void RefreshItems_should_return_searched_folders_test()
{
// arrange
Mapper.Initialize(cfg =>
{
cfg.AddProfiles(Assembly.GetExecutingAssembly());
});
_searchFoldersViewModel.SearchTerm = "anything";
_docHubConnectionContext
.Setup(d => d.Repository.SearchFolders("default", "anything"))
.Returns(_searchedFolders); // _searchedFolders has two items
// action
var searchTask = _searchFoldersViewModel.RefreshItems();
searchTask.Wait();
// assert
Assert.AreEqual(_searchFoldersViewModel.Items.Count, 2);
}