DbSet Find with Moq (EntityFramework.Testing.Moq)

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):

// Create some test data
var data = new List<Blog>
{
    new Blog{ Id = 1, Name = "BBB" },
    new Blog{ Id = 2, Name = "CCC" },
    new Blog{ Id = 3, Name = "AAA" }
};

// Create a mock set and context
var set = new Mock<DbSet<Blog>>()
    .SetupData(data);

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();

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!

+4
source share
1 answer

SetupData

public static Mock<DbSet<TEntity>> SetupData<TEntity>(this Mock<DbSet<TEntity>> mock, ICollection<TEntity> data = null, Func<object[], TEntity> find = null) where TEntity : class

, . , .

:

var set = new Mock<DbSet<Blog>>()
    .SetupData(data, objects => data.SingleOrDefault(d => d.Id == (int) objects.First()));
+3

Source: https://habr.com/ru/post/1606296/


All Articles