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

查看:18
本文介绍了如何为 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 是一个 扩展方法,它们是

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

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

Mocking with 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天全站免登陆