Unit Testing and Mocking MongoDB Extension Method in ASP.NET Core – Part1
In this post, we will see howto Unit Test and Mock MongoDB extension method. Look at how to mock complex Synchronous or Asynchronous extension methods in MongoDB.
We will see the approach to unit test InsertOneAsync or UpdateOne or UpdateMany or UpdateManyAsync.
Today in this article, we will cover below aspects,
In this post, we will look at the Create/Insert operation where we perform the insertion of new records into the database.
Please see below the sample code for which we shall write unit testing.
public async Task Create(TEntity obj)
{
if(obj == null)
{
throw new ArgumentNullException(typeof(TEntity).Name + " object is null");
}
_dbCollection = _mongoContext.GetCollection<TEntity>(typeof(TEntity).Name);
await _dbCollection.InsertOneAsync(obj);
}
We shall be using the same naming conventions for unit testing that we learned in our last article,
Below is an example of how we can mock and write unit testing
Unit Test 1
As shown above, the target method is Asynchronous. We shall write a method with the ‘await’ keyword in our Unit test case.
[Fact]
public async void BookRepository_CreateNewBook_Valid_Success()
{
//Arrange
_mockCollection.Setup(op=> op.InsertOneAsync(_book, null,
default(CancellationToken))).Returns(Task.CompletedTask);
_mockContext.Setup(c => c.GetCollection<Book>
(typeof(Book).Name)).Returns(_mockCollection.Object);
var bookRepo = new BookRepository(_mockContext.Object);
//Act
await bookRepo.Create(_book);
//Assert
//Verify if InsertOneAsync is called once
_mockCollection.Verify(c => c.InsertOneAsync(_book, null, default(CancellationToken)), Times.Once);
}
Unit Test 2
We shall write a test for capturing the specific exception. Here we are raising ‘ArgumentNullException’ in the target method.
[Fact]
public async void BookRepository_CreateNewBook_Null_Book_Failure()
{
// Arrange
_book = null;
//Act
var bookRepo = new BookRepository(_mockContext.Object);
// Assert
await Assert.ThrowsAsync<ArgumentNullException>(() => bookRepo.Create(_book));
}
Sometimes framework-dependent extension methods are really difficult to test. In such scenarios, we should only test for its execution once or twice, etc. rather than actual results.
We can very much make use of the Assertion method like ‘Verify’ to validate the same.
Using the above similar approach you can unit test other extension methods like UpdateOne or UpdateMany or UpdateManyAsync.
Mocking IAsyncCursor: MongoDB Mock and Unit Test a method returning IAsyncCursor
Do you have any better suggestions to test the method with AsyncCursor?
Please sound off your comments below!
References :
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.