简体   繁体   中英

Unit Testing Async Methods

I'm having some problems unit testing async methods.

Here's my unit test code:

        [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);
    }

When I run this test, it appears to never get past the first await statement. If it helps, here are the methods under test:

    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!");
        }
    }

Any help would be appreciated. Thanks.

Your Task s are never started. Try using Task.Run instead of the Task constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM