如何为Microsoft.EntityFrameworkCore 3.1方法FirstOrDefaultAsync创建xunit测试? [英] How to create xunit test for Microsoft.EntityFrameworkCore 3.1 method FirstOrDefaultAsync?

查看:59
本文介绍了如何为Microsoft.EntityFrameworkCore 3.1方法FirstOrDefaultAsync创建xunit测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我用于基本存储库的代码块.

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>();
}

我收到此错误,

EntityFrameworkQueryableExtensions.FirstOrDefaultAsync()不能在设置/验证表达式中使用

EntityFrameworkQueryableExtensions.FirstOrDefaultAsync() may not be used in setup / verification expressions

推荐答案

FirstOrDefaultAsync

FirstOrDefaultAsync is an extension method, which are

一种特殊的静态方法,但是它们被称为扩展类型上的实例方法.

a special kind of static method, but they are called as if they were instance methods on the extended type.

与Moq进行模拟(根据我对测试方法的了解,我假设您正在使用的 Moq)创建了一个从抽象接口派生的代理对象班级.由于静态扩展方法不是抽象类接口的一部分,因此无法模拟该方法.(请参阅此问题.)

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. Since the static extension method is not a part of your interface of abstract class, you can't mock that method. (See this question.)

不幸的是, Where 也是一种扩展方法,这意味着您也无法对此进行模拟.

Unfortunately, Where is an extension method, too, which means, that you cannot mock that, too.

无论如何,如果用户存储库只不过是在EF周围提供了一个(封装的)额外层而已,我认为嘲笑EF根本没有任何优点.我也为一切必须可交换并模拟为单元测试类的谬论而迷惑,这对逻辑很好(虽然不一定必要,但这是另外一个故事),但在您的情况下值得怀疑.

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. 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.

这篇关于如何为Microsoft.EntityFrameworkCore 3.1方法FirstOrDefaultAsync创建xunit测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆