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.
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);
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