[英]How to create xunit test for Microsoft.EntityFrameworkCore 3.1 method FirstOrDefaultAsync?
This is my code block for a base repo.这是我的基础回购代码块。
public async Task<T> ReadAsync(Expression<Func<T, bool>> where = null)
{
return await this.dbSet.Where(where).FirstOrDefaultAsync<T>();
}
I am getting this error,我收到此错误,
EntityFrameworkQueryableExtensions.FirstOrDefaultAsync() may not be used in setup / verification expressions EntityFrameworkQueryableExtensions.FirstOrDefaultAsync() 不能用于设置/验证表达式
FirstOrDefaultAsync
is an extension method , which are FirstOrDefaultAsync
是一个扩展方法,它们是
a special kind of static method, but they are called as if they were instance methods on the extended type.一种特殊的静态方法,但它们被称为扩展类型的实例方法。
Mocking with Moq (I assume that it is Moq that you are using, as far as I can tell from what I see of your test methods) creates a proxy object derived from an interface of abstract class.使用 Moq 进行模拟(我假设您正在使用的是Moq,就我对您的测试方法的了解而言)创建一个从抽象类的接口派生的代理对象。 Since the static extension method is not a part of your interface of abstract class , you can't mock that method.由于静态扩展方法不是抽象类接口的一部分,因此您不能模拟该方法。 ( See this question. ) ( 见这个问题。 )
Unfortunately, Where
is an extension method, too, which means, that you cannot mock that, too.不幸的是, Where
也是一个扩展方法,这意味着你也不能嘲笑它。
Anyway, if the user repository does nothing more than providing an (encapsulated) extra layer around EF, I'd argue that mocking EF has no merit at all.无论如何,如果用户存储库只是在 EF 周围提供一个(封装的)额外层,我认为模拟 EF 根本没有任何价值。 Me too fell for the fallacy that everything has to be swappable and mocked out to unit-test classes, which is fine for logic (albeit not necessarily necessary, but that's another story), but questionable in your case.我也陷入了这样一种谬论,即一切都必须可交换并模拟到单元测试类,这对逻辑来说很好(虽然不一定必要,但那是另一回事),但在你的情况下是有问题的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.