<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>how to mock mongodb repository c# - TheCodeBuzz</title>
	<atom:link href="https://thecodebuzz.com/tag/how-to-mock-mongodb-repository-c/feed/" rel="self" type="application/rss+xml" />
	<link>https://thecodebuzz.com</link>
	<description>Best Practices for Software Development</description>
	<lastBuildDate>Wed, 24 Jan 2024 02:50:11 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://thecodebuzz.com/wp-content/uploads/2022/11/cropped-android-chrome-512x512-1-1-51x51.jpg</url>
	<title>how to mock mongodb repository c# - TheCodeBuzz</title>
	<link>https://thecodebuzz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>MongoDB &#8211; Mock and Unit Test MongoCollection</title>
		<link>https://thecodebuzz.com/mongodb-mock-unit-test-imongocollection-net-core/</link>
					<comments>https://thecodebuzz.com/mongodb-mock-unit-test-imongocollection-net-core/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 11 Aug 2022 14:44:00 +0000</pubDate>
				<category><![CDATA[Mongo]]></category>
		<category><![CDATA[how to mock mongodb collection]]></category>
		<category><![CDATA[how to mock mongodb repository c#]]></category>
		<category><![CDATA[mock mongodb c# xunit]]></category>
		<category><![CDATA[mock<ifindfluent]]></category>
		<category><![CDATA[mongodb mock python]]></category>
		<category><![CDATA[mongodb unit test]]></category>
		<category><![CDATA[mongodb unit test golang.]]></category>
		<category><![CDATA[unit test mongodb c#]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=23433</guid>

					<description><![CDATA[<p>MongoDB &#8211; 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 [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/mongodb-mock-unit-test-imongocollection-net-core/">MongoDB – Mock and Unit Test MongoCollection</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">MongoDB &#8211; Mock and Unit Test MongoCollection</h1>



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



<p></p>



<p>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.</p>



<p></p>



<p>Below is a sample code for the Mocking MongoCollection class</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
        var settings = new MongoCollectionSettings();
            var mockCollection = new Mock&lt;IMongoCollection&lt;Book&gt;&gt; { DefaultValue = DefaultValue.Mock };
            mockCollection.SetupGet(s =&gt; s.DocumentSerializer).Returns(settings.SerializerRegistry.GetSerializer&lt;Book&gt;());
            mockCollection.SetupGet(s =&gt; s.Settings).Returns(settings);
            return mockCollection;
</pre></div>


<p></p>



<p>Above the &#8220;<strong>Book</strong>&#8221; class is a model object supporting book schema within the MongoDB database.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
public class Book
    {
        &#x5B;BsonId]
        &#x5B;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; }
    }
</pre></div>


<p></p>



<p>Below is a sample example using the above mock scenario,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
       &#x5B;Fact]
        public async void Test_GetBooksAsync_Verify()
        {
            //Arrange
            var mockContext = new Mock&amp;lt;IMongoContext&gt;();
            var mockCollection = CreateMockCollection();
            var collection = mockCollection.Object;

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

            BookstoreDatabaseSettings setting = new BookstoreDatabaseSettings();
            setting.BooksCollectionName = &quot;Book&quot;;
            var mockIDBsettings = new Mock&amp;lt;IOptions&amp;lt;BookstoreDatabaseSettings&gt;&gt;();

            mockContext.Setup(x =&gt; x.GetCollection&amp;lt;Book&gt;(&quot;Book&quot;)).Returns(mockCollection.Object);
            mockIDBsettings.Setup(x =&gt; x.Value).Returns(setting);

            //Act

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

            //ASSERT
            mockContext.Verify(x =&gt; x.GetCollection&amp;lt;Book&gt;(&quot;Book&quot;), Times.Once);
            mockCollection.Verify(m =&gt; m.FindAsync&amp;lt;Book&gt;(FilterDefinition&amp;lt;Book&gt;.Empty, null, CancellationToken.None), Times.Once);
        }
</pre></div>


<p></p>



<p>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 <a href="https://www.thecodebuzz.com/unit-testing-controller-sync-and-async-methods-asp-net-core-example/" target="_blank" rel="noopener" title="Unit Test and Mock Sync/Async Controller Methods in ASP.NET Core">verify controller methods</a></p>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p><p>The post <a href="https://thecodebuzz.com/mongodb-mock-unit-test-imongocollection-net-core/">MongoDB – Mock and Unit Test MongoCollection</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/mongodb-mock-unit-test-imongocollection-net-core/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Unit Test and Mock MongoDB extension Method in ASP.NET Core</title>
		<link>https://thecodebuzz.com/mongodb-driver-mocking-unit-testing-iasynccursor-async-method-part1/</link>
					<comments>https://thecodebuzz.com/mongodb-driver-mocking-unit-testing-iasynccursor-async-method-part1/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Fri, 01 Jan 2021 00:00:00 +0000</pubDate>
				<category><![CDATA[.NET Core]]></category>
		<category><![CDATA[findasync mongodb unit test]]></category>
		<category><![CDATA[how to mock mongodb collection]]></category>
		<category><![CDATA[how to mock mongodb repository c#]]></category>
		<category><![CDATA[in-memory mongodb for testing c#]]></category>
		<category><![CDATA[Iterate and Read using IAsyncCursor]]></category>
		<category><![CDATA[jest mock mongodb]]></category>
		<category><![CDATA[mock IAsyncCursor]]></category>
		<category><![CDATA[Mock IAsyncCursor in MongoDB driver]]></category>
		<category><![CDATA[mock mongodb c# xunit]]></category>
		<category><![CDATA[mock mongodb extension methods]]></category>
		<category><![CDATA[mongodb mock unit test java]]></category>
		<category><![CDATA[unit test mongodb nodejs]]></category>
		<category><![CDATA[Unit Testing and Mocking MongoDB Extension Method in ASP.NET Core]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=6308</guid>

					<description><![CDATA[<p>Unit Testing and Mocking MongoDB Extension Method in ASP.NET Core &#8211; 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 [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/mongodb-driver-mocking-unit-testing-iasynccursor-async-method-part1/">Unit Test and Mock MongoDB extension Method in ASP.NET Core</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading"><strong>Unit Testing and Mocking MongoDB Extension Method in ASP.NET Core &#8211; Part1</strong></h1>



<figure class="wp-block-image is-resized"><img fetchpriority="high" decoding="async" width="1315" height="924" src="https://i2.wp.com/thecodebuzz.com/wp-content/uploads/2019/11/Mocking-and-Unit-Testing-method-that-returns-IAsyncCursor-with-example-c-3.jpg?fit=785%2C552&amp;ssl=1" alt="Unit Test and Mock MongoDB extension" class="wp-image-6405" style="aspect-ratio:1.4273743016759777;width:595px;height:auto" srcset="https://thecodebuzz.com/wp-content/uploads/2019/11/Mocking-and-Unit-Testing-method-that-returns-IAsyncCursor-with-example-c-3.jpg 1315w, https://thecodebuzz.com/wp-content/uploads/2019/11/Mocking-and-Unit-Testing-method-that-returns-IAsyncCursor-with-example-c-3-300x211.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/11/Mocking-and-Unit-Testing-method-that-returns-IAsyncCursor-with-example-c-3-1024x720.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/11/Mocking-and-Unit-Testing-method-that-returns-IAsyncCursor-with-example-c-3-768x540.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/11/Mocking-and-Unit-Testing-method-that-returns-IAsyncCursor-with-example-c-3-740x520.jpg 740w" sizes="(max-width: 1315px) 100vw, 1315px" /></figure>



<p>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<strong> MongoDB. </strong></p>



<p></p>



<p>We will see the approach to unit test<em> <strong>InsertOneAsync </strong>or <strong>UpdateOne </strong>or <strong>UpdateMany </strong>or <strong>UpdateManyAsync</strong></em>.</p>



<p></p>



<p>Today in this article, we will cover below aspects,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-unit-test-1">Unit Test 1</a></li><li><a href="#aioseo-unit-test-2">Unit Test 2</a></li></ul></div>



<p></p>



<p>In this post, we will look at the Create/Insert operation where we perform the insertion of new records into the database.</p>



<p></p>



<p>Please see below the sample code for which we shall write unit testing.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
   


public async Task Create(TEntity obj)
        {
            if(obj == null)
            {
                throw new ArgumentNullException(typeof(TEntity).Name + &quot; object is null&quot;);
            }
            _dbCollection = _mongoContext.GetCollection&lt;TEntity&gt;(typeof(TEntity).Name);

            await _dbCollection.InsertOneAsync(obj);
        }




</pre></div>


<p></p>



<p>We shall be using the same naming conventions for unit testing that we learned in our last article,</p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/tdd-unit-testing-naming-conventions-and-standards/" target="_blank" rel="noreferrer noopener"><em><strong>How to Name Unit Test Cases &#8211; Best Practices</strong></em></a></li>
</ul>



<p></p>



<p>Below is an example of how we can mock and write unit testing </p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-unit-test-1">Unit Test 1</h2>



<p></p>



<p>As shown above, the target method is Asynchronous. We shall write a method with the &#8216;await&#8217; keyword in our Unit test case.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
        
        &#x5B;Fact]
        public async void BookRepository_CreateNewBook_Valid_Success()
        {
            //Arrange
            _mockCollection.Setup(op=&gt; op.InsertOneAsync(_book, null,
            default(CancellationToken))).Returns(Task.CompletedTask);

            _mockContext.Setup(c =&gt; c.GetCollection&lt;Book&gt; 
    (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 =&gt; c.InsertOneAsync(_book, null, default(CancellationToken)), Times.Once);
        }

</pre></div>


<p></p>



<h2 class="wp-block-heading" id="aioseo-unit-test-2">Unit Test 2</h2>



<p></p>



<p>We shall write a test for capturing the specific exception. Here we are raising <strong>&#8216;ArgumentNullException&#8217;</strong> in the target method.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
       
        &#x5B;Fact]
        public async void BookRepository_CreateNewBook_Null_Book_Failure()
        {
             // Arrange
            _book = null;

            //Act 
            var bookRepo = new BookRepository(_mockContext.Object);

            // Assert
            await Assert.ThrowsAsync&amp;lt;ArgumentNullException&gt;(() =&gt; bookRepo.Create(_book));
        }

</pre></div>


<p></p>



<p>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. </p>



<p></p>



<p>We can very much make use of the Assertion method like &#8216;Verify&#8217; to validate the same.</p>



<p></p>



<p></p>



<p>Using the above similar approach you can unit test other extension methods like <em><strong>UpdateOne </strong>or <strong>UpdateMany </strong>or <strong>UpdateManyAsync</strong></em>.</p>



<p></p>



<p></p>



<p>Mocking <strong><em>IAsyncCursor</em></strong>:  <a href="https://www.thecodebuzz.com/mongodb-driver-mocking-unit-testing-iasynccursor-async-method/" target="_blank" rel="noreferrer noopener"><strong><em>MongoDB Mock and Unit Test a method returning IAsyncCursor</em></strong></a></p>



<p></p>



<p>Do you have any better suggestions to test the method with AsyncCursor?</p>



<p></p>



<p>Please sound off your comments below!</p>



<p></p>



<p><strong><em>References </em></strong>: </p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/mongodb-c-driver-net-core-examples-getting-started/" target="_blank" rel="noreferrer noopener" title="Getting Started MongoDB in .NET Core with Examples"><em><strong>Getting Started MongoDB in .NET Core with Examples</strong></em></a></li>
</ul>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/mongodb-repository-implementation-unit-testing-net-core-example/" title="MongoDB Repository implementation in .NET Core with example"><strong><em>MongoDB Repository implementation in .NET Core with example</em></strong></a></li>
</ul>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p><p>The post <a href="https://thecodebuzz.com/mongodb-driver-mocking-unit-testing-iasynccursor-async-method-part1/">Unit Test and Mock MongoDB extension Method in ASP.NET Core</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/mongodb-driver-mocking-unit-testing-iasynccursor-async-method-part1/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
