Hello,
My app is working well. But when I try to create unit test, the entity framework is not working well
I am trying to make Unit Testing for my Entity Framework, but when I try to get data / write data from server I am getting this error:
System.ObjectDisposedException : 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.
Object name: 'FB_SERVICEContext'.
What is the culprit actually? Need advice.
Unit Test:
[TestFixture()]
public class FileControllerTests
{
private DependencyResolver _dependencyResolver;
public FileController _controller { get; set; }
public FB_SERVICEContext _context { get; set; }
public FileImageDataService _service { get; set; }
public ParamAppService _param{ get; set; }
public LogErrorService _logger { get; set; }
[SetUp]
public void Setup()
{
var webHost = WebHost.CreateDefaultBuilder().ConfigureAppConfiguration((context, config) =>
{
IHostEnvironment env = context.HostingEnvironment;
config.AddEnvironmentVariables()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.Development.json", optional: true);
})
.UseStartup<Startup>()
.Build();
_dependencyResolver = new DependencyResolver(webHost);
var oService = _dependencyResolver.GetService<FileImageDataService>();
var oLogger = _dependencyResolver.GetService<LogErrorService>();
var oParam = _dependencyResolver.GetService<ParamAppService>();
var oConfig = _dependencyResolver.GetService<IConfiguration>();
var builder = new DbContextOptionsBuilder<FB_SERVICEContext>()
.UseInMemoryDatabase("FB_SERVICE");
_context = new FB_SERVICEContext(builder.Options);
_service = oService;
_param = oParam;
_logger = oLogger;
_controller = new FileController(oService, oLogger, _param);
}
[Test()]
public async Task GetByIdTestAsync()
{
var response = await _controller.DownloadFileByFileName("DIRECTSALES", "F8C22188-28CC-48CF-8C20-786B6BD15B70.jpg");
Assert.Fail();
}
}
What I have tried:
Startup :
services.AddDbContext<FB_SERVICEContext>(opt => opt.UseSqlServer(Configuration.GetSection("ConnectionString:SqlServer").Value));
services.AddScoped<FileImageDataService>();
services.AddScoped<LogErrorService>();
services.AddScoped<ParamAppService>();