I used Moq objects along with the EntityFramework.Testing.Moq extension , and I recently hit a hit while trying to make Find. What I thought was right just makes the following installation (from the documentation):
var data = new List<Blog>
{
new Blog{ Id = 1, Name = "BBB" },
new Blog{ Id = 2, Name = "CCC" },
new Blog{ Id = 3, Name = "AAA" }
};
var set = new Mock<DbSet<Blog>>()
.SetupData(data);
var context = new Mock<BloggingContext>();
context.Setup(c => c.Blogs).Returns(set.Object);
var controller = new BlogsController(context.Object);
var result = await controller.Index();
In the controller, I could do this (again, from the document):
var query = db.Blogs.OrderBy(b => b.Name);
But then, when I tried to find DbSet Find, like this, using the model key:
var b = db.Blogs.Find(1);
I would return zero.
Now I was able to do this work by completing the following settings:
context.Setup(m => m.Blogs.Find(It.IsAny<int>()))
.Returns<object[]>(s => data.Find(d => d.Blogs == (int)s[0]));
but it remains for me to wonder if I am not doing something wrong in the first place, and if I am complicating something.
Thanks for any suggestions!
source
share