我尝试测试我的应用程序,所以我需要模拟我的EF上下文。
我的代码似乎还可以,但是我有以下异常:
“ System.ArgumentNullException:值不能为空。参数名称:source”
这是我的测试方法:
var options = new DbContextOptionsBuilder<ProductContext>().Options;
var settings = new SqlSettings
{
InMemory = true
};
var context = new Mock<ProductContext>(options, settings);
var mockTreeService = new TreeService(context.Object);
await mockTreeService.CreateTreeAsync("Testing tree", Guid.NewGuid());
context.Verify(x => x.AddAsync(It.IsAny<Tree>(), CancellationToken.None), Times.Once);
看起来在执行这段代码期间抛出了此异常
var tree = await _context.Trees
.Include(x => x.Translation)
.FirstOrDefaultAsync(x => x.Translation.Pl == name);
它来自我正在测试的服务
我认为这是由于没有设置连接字符串。坦白说,要完全模拟出来有点困难DbContext
,这就是EF Core团队提供内存中实现的原因。为了测试目的,这要容易得多。只需将您的options
初始化更改为:
var options = new DbContextOptionsBuilder<ProductContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
之后,您需要使用测试数据填充数据库。然后,您可以运行其余测试。
注意:如果您使用的是内存数据库,则不再需要模拟上下文,因此可以删除该部分代码。内存数据库本质上是一个模拟。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句