gpt4 book ai didi

c# - 单元测试异步方法

转载 作者:行者123 更新时间:2023-11-30 14:13:33 28 4
gpt4 key购买 nike

我在单元测试异步方法时遇到了一些问题。

这是我的单元测试代码:

        [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 构造函数。

关于c# - 单元测试异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13981067/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com