While mocking my ApplictionDbContext
I got error on method AddOrUpdate
.
DbSet
in context is virtual.
Under test method:
this.db.ExpensesDocuments.AddOrUpdate(doc);
My testing method:
[Fact]
public void AddOrUpdateExpenses_Success()
{
// arrange
var mockSet = new Mock<DbSet<ExpensesDocument>>();
var mockContext = new Mock<ApplicationDbContext>();
mockContext.Setup(m => m.ExpensesDocuments).Returns(mockSet.Object);
var provider = new ExpensesProvider(mockContext.Object);
// act
bool result = provider.AddOrUpdateExpenses(new ExpensesDocument());
// assert
}
The error:
Result Message: System.InvalidOperationException : Unable to call public, instance method AddOrUpdate on derived IDbSet type 'Castle.Proxies.DbSet`1Proxy'. Method not found.
I am using Moq4
framework for mocking and xUnit
for testing.
The AddOrUpdate extension method is described like this:
"Adds or updates entities by key when SaveChanges is called. Equivalent to an "upsert" operation from database terminology. This method can useful when seeding data using Migrations."
I found when trying to mock this that I was actually using it entirely wrong. The bit about the "useful when seeding" got me thinking. You don't need to call this to update an entity object. SaveChanges() does the trick as long as you have gotten the object from the context.
Probably not the answer you were hoping for (and 6 months late), but maybe someone else will reconsider their use of the method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With