C#   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c# – 单元测试异步方法大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我在单元测试异步方法时遇到了一些问题.

这是我的单元测试代码

[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# – 单元测试异步方法全部内容,希望文章能够帮你解决c# – 单元测试异步方法所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。