模拟实体框架核心上下文 [英] Mocking Entity Framework Core context
问题描述
我尝试测试我的应用,所以我需要模拟我的EF上下文.
I try to test my app so I need to mock my EF context.
我的代码似乎还可以,但是我有以下异常:
My code seems to be ok, but I have following exception:
"System.ArgumentNullException:值不能为null.参数名称: 来源"
"System.ArgumentNullException : Value cannot be null. Parameter name: 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);
在执行这段代码期间,似乎抛出了此异常
It looks like that this exception is thrown during executing this piece of code
var tree = await _context.Trees
.Include(x => x.Translation)
.FirstOrDefaultAsync(x => x.Translation.Pl == name);
它来自我正在测试的服务
It comes from my service which I'm testing
推荐答案
我认为这是由于没有设置连接字符串.坦白说,要完全模拟DbContext
有点困难,这就是EF Core团队提供内存中实现的原因.出于测试目的,这要容易得多.只需将您的options
初始化更改为:
I think this is due to not having a connection string set. Frankly, it's a bit difficult to fully mock out DbContext
, which is why the EF Core team has provided an in-memory implementation. This is far easier to work with for testing purposes. Just change your options
initialization to:
var options = new DbContextOptionsBuilder<ProductContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
然后,您需要用测试数据填充数据库.然后,您可以运行其余测试.
Afterwards, you'll need to populate the database with your test data. Then, you can run the rest of your test.
注意:如果您使用的是内存数据库,则不再需要模拟上下文,因此可以删除该部分代码.内存数据库本质上是一个模拟.
这篇关于模拟实体框架核心上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!