Failed to call AddOrUpdate public instance method, mocking

While taunting ApplictionDbContext , I got an error in the AddOrUpdate method.

DbSet in context is virtual.

In the 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 } 

Error:

Result message: System.InvalidOperationException: Cannot call public, the AddOrUpdate instance method for the derived type IDbSet 'Castle.Proxies.DbSet`1Proxy. Method not found.

I use the Moq4 framework for bullying and xUnit for testing.

+5
source share
1 answer

The AddOrUpdate extension method is described as follows:

"Adds or updates objects by key when calling SaveChanges. Equivalent to the" upsert "operation from database terminology. This method can be useful when sowing data using Migrations."

I found myself trying to mock it, that I was actually using it incorrectly. A little about the "useful when sowing" made me think. You do not need to call this to update the entity object. SaveChanges () does the trick until you get the object out of context.

Probably not the answer you hoped for (and 6 months later), but maybe someone else will review their use of the method.

+5
source

All Articles