Using InMemory database I'm trying to write a unit test which will check that a method is adding a record to a table. The record gets added in the class under test, but when i try and re-create I'm getting context disposed error. What is the correct way of setting up this test so that I can check the table in memory after the context has been disposed?
Unit Test
[Fact]
public void Test_AddContact_AddsSuccessfully()
{
var contextFactoryMock = new Mock<IContextFactory>();
contextFactoryMock.Setup(x => x.CreateContext()).Returns(CreateInMemoryContactContext());
var classUnderTest = new AddContact(contextFactoryMock.Object);
var response = classUnderTest.Run(new UkContactUsDto());
using (var ctx = contextFactoryMock.Object.CreateContext())
{
var items = ctx.ContactUs.ToList(); //<--- Exception happens here due to ctx being disposed
}
}
Create InMemory method
private ContactContext CreateInMemoryContactContext()
{
var _inMemoryContext = new ContactContext(new DbContextOptionsBuilder<ContactContext>().UseInMemoryDatabase((Guid.NewGuid().ToString())).Options);
return _inMemoryContext;
}
Method im testing
try
{
await using var ctx = _contextFactory.CreateContext();
ctx.ContactUs.Add(contactUs);
ctx.SaveChanges();
}
catch (Exception ex)
{
log.LogInformation(ex,"An error occured during contact us insertion.");
throw;
}
Error Message
Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.