【发布时间】:2019-08-12 22:56:13
【问题描述】:
我正在为我的 Web API 编写单元测试,除非删除包含(从方法中急切加载),否则无法通过测试。我正在使用内存数据库提供dbcontext,但无法弄清楚它为什么不返回任何数据。提前感谢任何帮助或建设性的批评
这是我要测试的方法。
注意:如果我注释掉 .include 语句,它通过测试。
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;
}
这是使用 inMemory DB 的基础 DbContext:
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;
}
这是测试:
[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);
}
}
这是我第一次编写单元测试,我基本上是边学边学。请随时指出您可能注意到的任何其他错误。
【问题讨论】:
-
您是否收到任何错误或意外结果?我对您的代码进行了测试,但未能重现您的问题。与我们分享一个可以重现您的问题的演示。
标签: c# unit-testing asp.net-core entity-framework-core xunit