I am writing unit tests for my my Web API and cannot get the test to pass except by removing the include (eager-loading from the method). I am using the in-memory database to provide the dbcontext and can't figure out why it is returning no data. Thanks in advance for any help or constructive criticism
This is the method I am trying to test.
Note: it passes the test if I comment out the .include statements.
public async Task<LibraryAsset> GetAsset(int assetId) { var asset = await _context.LibraryAssets .Include(p => p.Photo) .Include(p => p.Category) .Include(a => a.AssetType) .Include(s => s.Status) .Include(s => s.Author) .FirstOrDefaultAsync(x => x.Id == assetId); return asset; } This is the base DbContext using the inMemory DB:
public DataContext GetDbContext() { var builder = new DbContextOptionsBuilder<DataContext>(); if (useSqlite) { // Use Sqlite DB. builder.UseSqlite("DataSource=:memory:", x => { }); } else { // Use In-Memory DB. builder.UseInMemoryDatabase(Guid.NewGuid().ToString()); } var DataContext = new DataContext(builder.Options); if (useSqlite) { // SQLite needs to open connection to the DB. // Not required for in-memory-database and MS SQL. DataContext.Database.OpenConnection(); } DataContext.Database.EnsureCreated(); return DataContext; } This is the test:
[Fact] public async void GetAssetById_ExistingAsset_ReturnAsset() { using (var context = GetDbContext()) { ILogger<LibraryAssetService> logger = new NullLogger<LibraryAssetService>(); var service = new LibraryAssetService(context, _logger); var asset = new LibraryAsset { Id = 40, NumberOfCopies = 20, Title = "", Year = 1992, Status = new Status { Id = 1 }, AssetType = new AssetType { Id = 1 }, Author = new Author { Id = 1 }, Category = new Category { Id = 2 }, Photo = new AssetPhoto { Id = 1 } }; context.LibraryAssets.Attach(asset); context.Add(asset); context.SaveChanges(); var actual = await service.GetAsset(40); Assert.Equal(40, actual.Id); } } This is my first time writing unit tests and I am basically learning as I go. Please feel free to point out any other mistakes that you may have noticed as well.