Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock DbSet.Add() for Entity Framework Core?

I'm mocking a DbContext to auto-test classes that update the database.

I'm using Entity Framework Core and .NET 5.

Mock<MyDbContext> fakeDbContext = new Mock<MyDbContext>();

List<Book> availableBooks = new List<Book>(); // filled elsewhere

fakeDbContext.Setup(ct => ct.BookRepository).ReturnsDbSet(availableBooks);  

This works fine, up to

fakeDbContext.BookRepository.Add(newBook);

The data from newBook show neither in BookRepository not in availableBooks.

So I guess I have to mock Add() further (I thought Setup().ReturnsDbSet() handled that, mistakenly it appears).

That would be the easiest way to call availableBooks.Add(). However, it has to return an EntityEntry<Book> object, which I haven't yet found how to create (it has a constructor, but not recommended for regular use).

I can't find any documentation on the matter, however. What can I try next?

like image 754
Jean-David Lanz Avatar asked Oct 24 '25 03:10

Jean-David Lanz


1 Answers

It being understood that the right answer is this one, I also want the question to get a straight answer, if nothing else because a few people upvoted it.

As mentioned in the comments, I tried Moq.EntityFrameworkCore and failed.

I succeeded with MockQueryable:

Mock<MyDbContext> fakeDbContext = new Mock<MyDbContext>();

List<Book> availableBooks = new List<Book>(); // filled elsewhere

Mock<DbSet<Book>> fakeBookRepository = availableBooks.AsQueryable().BuildMockDbSet();
fakeBookRepository.Setup(rp => rp.Add(It.IsAny<Book>()))
                  .Callback((Book bk) => availableBooks.Add(bk));
PseudoContexteMAS.Setup(ct => ct.DepotLivraison)
                 .Returns(fakeBookRepository.Object);

There ya go.

like image 161
Jean-David Lanz Avatar answered Oct 27 '25 01:10

Jean-David Lanz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!