Using Moq to mock an Asynchronous Method in .NET Core Unit Tests

Unit Tests An Asynchronous Method In NET Core Example

Today in this article, we will learn how to Unit Tests An Asynchronous Method In .NET Core with examples. Below are a few examples of the .NET core-based common unit testing sample and their resolution using mocking.

Today in this article, we will cover below aspects,

Here I am testing a controller Method that makes an asynchronous call to an external service using HTTPClient.

        [HttpGet]
        public async Task<IActionResult> GetAsync(string id)
        {
            Book book = null;
            try
            {
                // Test await method - Asynchronously 
                book = await _bookService.GetAsync(id);
                book.Price = 10;
                if (book == null)
                {
                    return NotFound();
                }
            }
            catch(Exception ex)
            {
            }
            // do more stuff

            return Ok(book);
        }

Resolution

Below is an example of how we can write unit test cases,

We will follow the AAA pattern where we will perform Arrange, Act, and Assertion.

Below is an example of mocking the Async method of Interface.

   var mockBookClient= new Mock<IBookService>();
   mockBookClient.Setup(c => c.GetAsync(document .Id)).ReturnsAsync(document);

Below is a complete sample example,

       
        [Fact]
        public async Task BookService_GetBookAsync_With_ValidBookID()
        {
            //Arrange
            Book document = new Book()
            {
                Author = "The",
                BookName = "CodeBUzz",
                Id = "1234"
            };

            var mockBookClient= new Mock<IBookService>();
            mockBookClient.Setup(c => c.GetAsync(document .Id)).ReturnsAsync(document);

            //Act
            BooksController service = new BooksController(mockBookClient.Object);
            var result = await service.GetAsync(bookID);

            //Assert
            Assert.NotNull(result);

        }

Better Assertion

If you would like to do a more rigorous assert on the return object which is always recommended, please use the below code to perform better assertion.

Unit Tests An Asynchronous Method In NET Core Example

The below article mentions the checklist one should be aware of while Unit Testing an API Interface(Controller).

References :

Please note that we need to use ReturnsAsync instead of Returns to avail and set up the mock result using Moq for asynchronous operation.

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *