title: ASP.NET Testing DbContext in local methods
body: <p>I have an ASP.NET MVC project, and am writing my service something along the lines of this:</p>
  
  <pre><code>public class UserService : IUserService
  {
      public void AddUser(UserModel userModel)
      {
          if (ModelState.IsValid){
              var user = new User
              {
                  FirstName = userModel.FirstName,
                  LastName = userModel.LastName,
                  Email = userModel.Email,
                  Age = userModel.Age
              };
              using (var context = new MyDbContext())
              {
                  context.Users.Add(user);
              }
          }
      }
      //... More code for service
  }
  </code></pre>
  
  <p>And my DbContext class:</p>
  
  <pre><code>public class MyDbContext : DbContext 
  {
      public MyDbContext(): base("name=mydb"){}
  
      public DbSet&lt;User&gt; Users {get; set;}
  
      //.. More domain objects.
  }
  </code></pre>
  
  <p>This runs fine for the most part, but the problem arises when I want to try and test it. I'm following the general guidelines <a href="http://www.loganfranken.com/blog/517/mocking-dbset-queries-in-ef6/">here</a> with mocking it out, but that's only if the DbContext is declared as a class instance, as opposed to a functional variable. I want to do it this way because it enables me to have control over the transaction and context disposal. Anyone have any suggestions on how to do this?</p>
  
  <p>My mocks are like this:</p>
  
  <pre><code>public class UserServiceTest 
  {
      [Fact]
      public void TestAddUser()
      {
          var userSet = GetQueryableMockDbSet(userData.ToArray());
          var context = new MyDbContext
          {
              Users = userSet
          };
          var userService = new UserService();
          userService.AddUser(); // HOW DO I GET CONTEXT IN HERE?
      }   
  
      private static DbSet&lt;T&gt; GetQueryableMockDbSet&lt;T&gt;(params T[] sourceList) where T : class
          {
              var queryable = sourceList.AsQueryable();
  
              var dbSet = new Mock&lt;DbSet&lt;T&gt;&gt;();
              dbSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.Provider).Returns(queryable.Provider);
              dbSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.Expression).Returns(queryable.Expression);
              dbSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(queryable.ElementType);
              dbSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(queryable.GetEnumerator());
  
              return dbSet.Object;
          }
  }
  </code></pre>