'Writing data using Moq.EntityFrameworkCore

I'm attempting to use Moq.EntityFrameworkCore for unit testing. I'm having no problem with query operations that read the pre-seeded data. However write operations initially appear to work without throwing any exceptions but the underlying DbSet's don't reflect any newly added records. Any ideas what I may be missing to moq the write operations?

My moq db context setup code:

var dbContextMock = new Mock<MyDbContext>();

var submitterOperators = new List<SubmitterOperator>();
submitterOperators.Add(
    fixture.Build<SubmitterOperator>()
        .With(e => e.Deleted, false)
        .Without(e => e.Operation)
        .Create()
);
dbContextMock.Setup(x => x.SubmitterOperators).ReturnsDbSet(submitterOperators);

return dbContextMock.Object;

Code that tries to insert a new entity, that works successfully against an actual non-moq'd database:

await _dataContext.SubmitterOperators.AddAsync(entity);
await _dataContext.SaveChangesAsync();

But doesn't actually change the moq'd DbSet<SubmitterOperator> when unit testing.

I imagine I'm missing some scaffolding somewhere setting up my dbContextMock but I haven't found any examples to follow online around moq'ing data writes.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source