c# – 单元测试异步方法
发布时间:2020-12-16 01:52:02 所属栏目:百科 来源:网络整理
导读:我在单元测试异步方法时遇到了一些问题. 这是我的单元测试代码: [TestMethod] public async Task TestRefreshList_RefreshesList() { int countBeforeAdd = listViewModel.NotesTitles.Count; // Add a note. await listViewModel.NoteRepository.AddNoteAs
我在单元测试异步方法时遇到了一些问题.
这是我的单元测试代码: [TestMethod] public async Task TestRefreshList_RefreshesList() { int countBeforeAdd = listViewModel.NotesTitles.Count; // Add a note. await listViewModel.NoteRepository.AddNoteAsync(new Note { Title = String.Empty,Content = String.Empty }); // Refresh. await listViewModel.RefreshList(); int countAfterAdd = listViewModel.NotesTitles.Count; // Assert that the count increased by 1 and that it matches the count of the repository. Assert.IsTrue(countAfterAdd == countBeforeAdd + 1 && countAfterAdd == mockNoteRepository.FakeNotes.Count); } 当我运行此测试时,似乎永远不会超过第一个await语句.如果有帮助,以下是测试中的方法: public ObservableCollection<Note> FakeNotes { get; set; } public Task AddNoteAsync(Models.Note note) { return new Task(() => { FakeNotes.Add(note); }); } public Task<ObservableCollection<string>> GetAllNoteTitlesAsync() { // Return the titles of the notes in the FakeNotes collection. return new Task<ObservableCollection<string>>(() => { return new ObservableCollection<string>(FakeNotes.Select(n => n.Title)); }); } …. public async Task RefreshList() { try { NotesTitles = await NoteRepository.GetAllNoteTitlesAsync(); } catch (Exception) { Notifier.Notify("We encountered an error when trying to load your notes. Please try again. ","Ooops!"); } } 任何帮助,将不胜感激.谢谢. 解决方法
您的任务永远不会开始.尝试使用Task.Run而不是Task构造函数.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |