title: How to mock a MongoDB collection of type IMongoCollection<T> to return some predefined data?
body: <p>Below is my code:</p>
  
  <p><strong>Controller/Action:</strong>   </p>
  
  <pre><code>[HttpPost]
  [AllowAnonymous]
  [ValidateAntiForgeryToken]
  public async Task&lt;IActionResult&gt; Register(CustomerViewModel model, string returnUrl = null)
  {
      try
      {
          ViewData["ReturnUrl"] = returnUrl;
  
          // when debugging the test, _dbContext.Customers throws exception
          CustomerDoc existingCustomer = await _dbContext.Customers.Find(o =&gt; o.email == model.email).FirstOrDefaultAsync();
          if (existingCustomer != null)
          {
              ModelState.AddModelError("Email", "email already used.");
          }
          // other checkings 
  
          if (!ModelState.IsValid)
          {
              return View(model);
          }
  
          // if model state is valid, do something here
      }
      catch (Exception ex)
      {
          return View(model);
      }
  
      return View(model);
  }  
  </code></pre>
  
  <p><strong>And my unit test code is:</strong>   </p>
  
  <pre><code>[Fact]
  public async Task should_return_view_with_errors_when_email_already_exists()
  {
      IEnumerable&lt;CustomerDoc&gt; customers = new List&lt;CustomerDoc&gt;
      {
          new CustomerDoc
          {
              email = "test@test.com"
          }
      };
  
      _dbContextMock.SetupAllProperties();
  
      // below line is causing the error
      _dbContextMock.Setup(c =&gt; c.Customers).Returns(() =&gt;(IMongoCollection&lt;CustomerDoc&gt;)customers);
  
      CustomerViewModel model = new CustomerViewModel
      {
          email = "test@test.com"
      };
  
      CreateController();
  
      var result = await _controller.Register(model);
  
      Assert.IsType&lt;ViewResult&gt;(result);
      Assert.False(_controller.ModelState.IsValid);
      Assert.True(_controller.ModelState.ContainsKey("Email"));
  }
  </code></pre>
  
  <p>As you can see in my unit test code comment, I am trying to mock a IMongoCollection to return some data. But I am not able to do so because <strong>_dbContext.Customers</strong> is throwing exception.   </p>
  
  <p>How can I mock <strong>IMongoCollection</strong> to return some predefined data?</p>
  
  <p><strong>I am using</strong><br>
  asp.net core 2.1.0<br>
  mongodb driver 2.7.0</p>