Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to call public instance method AddOrUpdate, mocking

Tags:

c#

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.

like image 325
Nerf Avatar asked Jul 10 '15 09:07

Nerf


1 Answers

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.

like image 89
matsemann Avatar answered Oct 25 '22 01:10

matsemann