MongoDB – Mock and Unit Test MongoCollection

Today in this short tutorial, we will see how to Mock and Unit Test MongoCollection and IMongoCollection used in the MongoDB .NET driver library.

MongoCollection mocking could be useful considering the complex extension method supported by MongoDB drivers which is not only difficult to mock but also unit tested.

Below is a sample code for the Mocking MongoCollection class

        var settings = new MongoCollectionSettings();
            var mockCollection = new Mock<IMongoCollection<Book>> { DefaultValue = DefaultValue.Mock };
            mockCollection.SetupGet(s => s.DocumentSerializer).Returns(settings.SerializerRegistry.GetSerializer<Book>());
            mockCollection.SetupGet(s => s.Settings).Returns(settings);
            return mockCollection;

Above the “Book” class is a model object supporting book schema within the MongoDB database.

public class Book
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }

        public string BookName { get; set; }

        public decimal Price { get; set; }

        public string Category { get; set; }

        public string Author { get; set; }
    }

Below is a sample example using the above mock scenario,

       [Fact]
        public async void Test_GetBooksAsync_Verify()
        {
            //Arrange
            var mockContext = new Mock<IMongoContext>();
            var mockCollection = CreateMockCollection();
            var collection = mockCollection.Object;

            Book document = new Book();
            document.Author = "asdas";
            document.BookName = "sadasd";
            document.Id = ObjectId.GenerateNewId().ToString();
            mockCollection.Object.InsertOne(document);

            BookstoreDatabaseSettings setting = new BookstoreDatabaseSettings();
            setting.BooksCollectionName = "Book";
            var mockIDBsettings = new Mock<IOptions<BookstoreDatabaseSettings>>();

            mockContext.Setup(x => x.GetCollection<Book>("Book")).Returns(mockCollection.Object);
            mockIDBsettings.Setup(x => x.Value).Returns(setting);

            //Act

            BookService service = new BookService(mockIDBsettings.Object, mockContext.Object);
            var result = await service.GetBooksAsync();

            //ASSERT
            mockContext.Verify(x => x.GetCollection<Book>("Book"), Times.Once);
            mockCollection.Verify(m => m.FindAsync<Book>(FilterDefinition<Book>.Empty, null, CancellationToken.None), Times.Once);
        }

Above extension, methods are Asserted for verifying, if they are called in the code execution or not. Additionally, you can add more assertions for the results you get from the method. Please visit this article for more information on how to verify controller methods

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 *