Unit testing asynchronous code
Unit testing asynchronous code requires the same approach as writing good asynchronous C# code. If you need a refresher on how to work with async
methods, you can review Chapter 5.
When writing a unit test for an async
method, you will use the await
keyword to wait for the method to complete. This requires that your unit test method is async
and returns Task
. Just like other C# code, creating async void
methods is not permitted. Let’s look at a very simple test method:
[Fact]
private async Task GetBookAsync_Returns_A_Book()
{
// Arrange
BookService bookService = new();
var bookId = 123;
// Act
var book = await bookService.GetBookAsync(bookId);
// Assert
Assert.NotNull(book);
Assert.Equal(bookId, book.Id);
}
This probably...