[英]Unit Testing Async Methods
我在單元測試異步方法時遇到了一些問題。
這是我的單元測試代碼:
[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
永遠不會開始。 嘗試使用Task.Run
而不是Task
構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.