title: How to properly moq ExecuteQuery method within DataContext?
body: <p>I'm having a difficult time trying to understand how to appropriately return mocked data from a simulated database call in a unit test.</p>
  
  <p>Here's an example method I want to unit test (<strong>GetBuildings</strong>):</p>
  
  <pre><code>public class BuildingService : IBuildingService {
  
      public IQueryable&lt;Building&gt; GetBuildings(int propertyId)
      {
          IQueryable&lt;Building&gt; buildings;
  
          // Execution path for potential exception thrown
          // if (...) throw new SpecialException();
  
          // Another execution path...
          // if (...) ...
  
          using (var context = DataContext.Instance())
          {
              var Params = new List&lt;SqlParameter&gt;
              {
                  new SqlParameter("@PropertyId", propertyId)
              };
  
              // I need to return mocked data here...
              buildings = context
                .ExecuteQuery&lt;Building&gt;(System.Data.CommandType.StoredProcedure, "dbo.Building_List", Params.ToArray&lt;object&gt;())
                .AsQueryable();
  
  
          }
  
          return buildings;
      }
  
  }
  </code></pre>
  
  <p>So <strong>GetBuildings</strong> calls a stored procedure.</p>
  
  <p>So I need to mock the DataContext, that of which I can override and set a testable instance. So what happens here is, in the above example <code>DataContext.Instance()</code> does return the mocked object.</p>
  
  <pre><code>[TestFixture]
  public class BuildingServiceTests
  {
  
      private Mock&lt;IDataContext&gt; _mockDataContext;
  
      [SetUp]
      public void Setup() {
          _mockDataContext = new Mock&lt;IDataContext&gt;();
      }
  
      [TearDown]
      public void TearDown() {
          ...
      }
  
      [Test]
      public void SomeTestName() {
  
          _mockDataContext.Setup(r =&gt; 
              r.ExecuteQuery&lt;Building&gt;(CommandType.StoredProcedure, "someSproc"))
              .Returns(new List&lt;Building&gt;() { new Building() { BuildingId = 1, Title = "1" }}.AsQueryable());
  
        DataContext.SetTestableInstance(_mockDataContext.Object); 
          var builings = BuildingService.GetBuildings(1, 1);
  
        // Assert...
  
      }
  </code></pre>
  
  <p>Please ignore some of the parameters, like <code>propertyId</code>. I've stripped those out and simplified this all. I simply can't get the <code>ExecuteQuery</code> method to return any data.</p>
  
  <p>All other simple peta-poco type methods I can mock without issue (i.e. Get, Insert, Delete).</p>
  
  <p><strong>Update</strong></p>
  
  <p><code>DataContext.Instance</code> returns the active instance of the DataContext class, if exists, and if not exists, returns a new one. So the method of test under question returns the mocked instance.</p>