How to Mock Entity Framework Core Change Tracking

c# entity-framework-core mocking moq unit-testing

Question

I have a Mocked Context Setup like this.

// Creates a working Fake Db Set of FakeClass Type
var fakeDbSet = Mockings.CreateDbSetMock(fakeData);  
var fakeContext = new Mock<FakeContext>();  
fakeContext.Setup(c => c.FakeData).Returns(fakeDbSet);     

Access to the Context itself an the FakeData works as intended. But now I'm trying to write a Unit Test for a function which accesses the ChangeTracker of fakeContext.

ctx.ChangeTracker.AutoDetectChangesEnabled = false;  

Now the test fails and an Exception is thrown, because accessing the ChangeTracker of the mocked context returns null.

Is there a way to mock the ChangeTracker of the Context?

I already tried to setup the mocked Context with a mocked ChangeTracker, but I can't create a valid Instance, because it requieres the Context itself in the Constructor.

1
0
7/1/2019 5:25:40 PM

Popular Answer

In some cases mocking EF DbContext can be very tricky, however in most cases you do not need to (and you should not also) mock the DbContext. You can use InMemoryDatabase option instead of mocking the DbContext.(If you need functionalities such as DbQuery or any thing related to RDBMS, this will not help you)

 var options = new DbContextOptionsBuilder<MyContext>().UseInMemoryDatabase(databaseName: "MyInMemoryDB").Options;
 var ctx = new MyContext(options);

Read more about Testing In Memory

However if you insist on having the mocked DbContext, then take a look at this thread: https://forums.asp.net/t/2155192.aspx?Mocking+EF+Core+DBContext+with+ChangeTracker

0
2/27/2020 11:19:00 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow