-
Notifications
You must be signed in to change notification settings - Fork 34
Home
EntityFramework.Testing provides an implementation of IDbAsyncQueryProvider that can be used when testing a component that uses async queries with EntityFramework. You can read more about how to use these components at http://msdn.com/data/dn314429#async.
EntityFramework.Testing.Moq provides some helpful extensions to mock an Entity Framework context and it's DbSets using Moq.
For example, given the following MVC controller.
public class BlogsController : Controller
{
private readonly BloggingContext db;
public BlogsController(BloggingContext context)
{
db = context;
}
public async Task<ViewResult> Index()
{
var query = db.Blogs.OrderBy(b => b.Name);
return View(await query.ToListAsync());
}
}
You can write a unit test against an mock context as follows. MockDbSet and the SetupSeedData and SetupLinq extension methods are part of EntityFramework.Testing.Moq.
[TestMethod]
public async Task Index_returns_blogs_ordered_by_name()
{
// Create some test data
var data = new List<Blog>
{
new Blog{ Name = "BBB" },
new Blog{ Name = "CCC" },
new Blog{ Name = "AAA" }
};
// Create a mock set and context
var set = new MockDbSet<Blog>()
.SetupSeedData(data)
.SetupLinq();
var context = new Mock<BloggingContext>();
context.Setup(c => c.Blogs).Returns(set.Object);
// Create a BlogsController and invoke the Index action
var controller = new BlogsController(context.Object);
var result = await controller.Index();
// Check the results
var blogs = (List<Blog>)result.Model;
Assert.AreEqual(3, blogs .Count());
Assert.AreEqual("AAA", blogs[0].Name);
Assert.AreEqual("BBB", blogs[1].Name);
Assert.AreEqual("CCC", blogs[2].Name);
}
The following APIs can be used on a MockDbSet. You can chain together as many of them as needed to setup the required functionality for each test.
SetupSeedData(data)
SetupSeedData can be used to prepopulate the set with a well-known set of data.
var data = new List<Blog> { new Blog{ Name = "BBB" } };
var set = new MockDbSet<Blog>()
.SetupSeedData(data);
SetupLinq()
SetupLinq will enable the use of LINQ against the set (and direct enumeration of the set). This includes async LINQ operators.
var set = new MockDbSet<Blog>()
.SetupLinq();
SetUpAddAndRemove()
SetUpAddAndRemove will enable the DbSet.Add and DbSet.Remove methods to update the local data for the set.
var set = new MockDbSet<Blog>()
.SetUpAddAndRemove();
SetupFind(finder)
SetupFind allows you to specify a finder function that is used to find entities based on their key values when the DbSet.Find method is called.
var set = new MockDbSet<Blog>()
.SetupFind((keyValues, blog) => blog.BlogId == (int)keyValues.Single())