title: Mocking IDocumentQuery in Unit Test that uses Linq queries
body: <p>I am writing unit tests for <code>DocumentDBRepository</code> but I got a null reference exception. I use Moq framework and XUnit.</p>
  
  <p>Here's my methods in <code>DocumentDBRepository</code> class.</p>
  
    
  
  <pre class="lang-cs prettyprint-override"><code>public class DocumentDBRepository&lt;T&gt; : IRepository&lt;T&gt; where T: class
  {
      private static string DatabaseId;
      private static string CollectionId;
      private static IDocumentClient client;
      public DocumentDBRepository(IDocumentClient documentClient, string databaseId, string collectionId)
      {
          DatabaseId = databaseId;
          CollectionId = collectionId;
          client = documentClient;
          CreateDatabaseIfNotExistsAsync().Wait();
          CreateCollectionIfNotExistsAsync().Wait();
      }
  
      public async Task&lt;IDocumentQuery&lt;T&gt;&gt; GetQuery(Expression&lt;Func&lt;T, bool&gt;&gt; predicate)
      {
          try
          {
              IDocumentQuery&lt;T&gt; query = client.CreateDocumentQuery&lt;T&gt;(
            UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
            new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true })
            .Where(predicate)
            .AsDocumentQuery();
  
              return query;
          }
          catch (Exception e) {
              throw;
          }    
      }
  
      public async Task&lt;IEnumerable&lt;T&gt;&gt; GetEntities(IDocumentQuery&lt;T&gt; query)
      {
          try
          {
              List&lt;T&gt; results = new List&lt;T&gt;();
              while (query.HasMoreResults)
              {
                  results.AddRange(await query.ExecuteNextAsync&lt;T&gt;());
              }
  
              return results;
          }
          catch (Exception e)
          {
              throw;
          }            
      }
  }
  </code></pre>
  
  <p>Here's my test code:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public interface IFakeDocumentQuery&lt;T&gt; : IDocumentQuery&lt;T&gt;, IOrderedQueryable&lt;T&gt;
  {
  
  }
  
  [Fact]
  public async virtual Task Test_GetBooksById()
  {
  
      var expected = new List&lt;Book&gt; {
          new Book { ID = "123", Description = "HarryPotter"},
          new Book { ID = "124", Description = "HarryPotter2"} };
  
  
      var response = new FeedResponse&lt;Book&gt;(expected);
  
      var mockDocumentQuery = new Mock&lt;IFakeDocumentQuery&lt;Book&gt;&gt;();
  
      mockDocumentQuery.SetupSequence(_ =&gt; _.HasMoreResults)
                       .Returns(true)
                       .Returns(false);
  
      mockDocumentQuery.Setup(_ =&gt; _.ExecuteNextAsync&lt;Book&gt;(It.IsAny&lt;CancellationToken&gt;()))
                       .ReturnsAsync(response);
  
      var client = new Mock&lt;IDocumentClient&gt;();
  
      client.Setup(_ =&gt; _.CreateDocumentQuery&lt;Book&gt;(It.IsAny&lt;Uri&gt;(), It.IsAny&lt;FeedOptions&gt;()))
            .Returns(mockDocumentQuery.Object);
  
      var documentsRepository = new DocumentDBRepository&lt;Book&gt;(client.Object, "123", "123");
  
      //Act
      var query = await documentsRepository.GetQuery(t =&gt; t != null);
      var entities = await documentsRepository.GetEntities(query);
  
      //Assert
      if (entities != null)
      {
          entities.Should().BeEquivalentTo(expected);
      }
  }
  </code></pre>
  
  <p>Here's the error message after running the test method:</p>
  
  <blockquote>
    <p>Message: System.NullReferenceException : Object reference not set to
    an instance of an object.</p>
  </blockquote>
  
  <p>When I stepped through the code, the error happens right after the the test code called <code>GetQuery()</code> method:</p>
  
  <pre class="lang-cs prettyprint-override"><code> IDocumentQuery&lt;T&gt; query = client.CreateDocumentQuery&lt;T&gt;(
                UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
                new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true })
                .Where(predicate)
                .AsDocumentQuery();
  </code></pre>
  
  <p>Here's my thought process: when I stepped through the entire code, I do not see any null variables. But in the 'response' variable from the second line of the test method, it does show a lot of the properties are null exception but result view shows the 'expected' variable.</p>
  
  <p>My question is, is it because of the response variable that caused the null reference exception? Or somewhere else?</p>
  
  <p>PS: Test code reference from <a href="https://stackoverflow.com/questions/48349659/how-to-should-i-mock-documentclient-for-documentdb-unit-testing?noredirect=1&amp;lq=1">here</a></p>
  
  <p>I also tried turning on the Mock behavior to strict and saw this error message.</p>
  
  <blockquote>
    <p>Message: System.AggregateException : One or more errors occurred.
    (IDocumentClient.ReadDatabaseAsync(dbs/123, null) invocation failed
    with mock behavior Strict. All invocations on the mock must have a
    corresponding setup.)
    ---- Moq.MockException : IDocumentClient.ReadDatabaseAsync(dbs/123, null) invocation failed with mock behavior Strict. All invocations on
    the mock must have a corresponding setup.</p>
  </blockquote>