.NET 8 Moq mock GetRequiredKeyedService Setup报错
.NET 8 Moq mock GetRequiredKeyedService Setup报错
代码有地方用到了IServiceProvider.GetRequiredKeyedService来解析服务,写单元测试时也需要Mock它,本以为像下面这些些就可以
var serviceProvider = new Mock<IServiceProvider>();
serviceProvider.Setup(x => x.GetRequiredKeyedService<AAA>(It.IsAny<BBB>())).Returns(new CCC());
没想到报错了:
Test method threw exception:
System.NotSupportedException: Unsupported expression: x => x.GetRequiredKeyedService(It.IsAny<Type>(), It.IsAny<object>())
Extension methods (here: ServiceProviderKeyedServiceExtensions.GetRequiredKeyedService) may not be used in setup / verification expressions.
Stack Trace:
Guard.IsOverridable(MethodInfo method, Expression expression) line 87
MethodExpectation.ctor(LambdaExpression expression, MethodInfo method, IReadOnlyList`1 arguments, Boolean exactGenericTypeArguments, Boolean skipMatcherInitialization, Boolean allowNonOverridable) line 236
ExpressionExtensions.<Split>g__Split|5_0(Expression e, Expression& r, MethodExpectation& p, Boolean assignment, Boolean allowNonOverridableLastProperty) line 256
ExpressionExtensions.Split(LambdaExpression expression, Boolean allowNonOverridableLastProperty) line 170
Mock.SetupRecursive[TSetup](Mock mock, LambdaExpression expression, Func`4 setupLast, Boolean allowNonOverridableLastProperty) line 728
Mock.Setup(Mock mock, LambdaExpression expression, Condition condition) line 562
Mock`1.Setup[TResult](Expression`1 expression) line 645
有点奇怪,难道GetRequiredKeyedService不是接口方法?查看.NET源代码,果然,GetRequiredKeyedService是IServiceProvider的扩招方法,我们知道Moq是不支持Setup扩招方法的。
/// <summary>
/// Get service of type <typeparamref name="T"/> from the <see cref="IServiceProvider"/>.
/// </summary>
/// <typeparam name="T">The type of service object to get.</typeparam>
/// <param name="provider">The <see cref="IServiceProvider"/> to retrieve the service object from.</param>
/// <param name="serviceKey">An object that specifies the key of service object to get.</param>
/// <returns>A service object of type <typeparamref name="T"/>.</returns>
/// <exception cref="System.InvalidOperationException">There is no service of type <typeparamref name="T"/>.</exception>
public static T GetRequiredKeyedService<T>(this IServiceProvider provider, object? serviceKey) where T : notnull
{
ThrowHelper.ThrowIfNull(provider);
return (T)provider.GetRequiredKeyedService(typeof(T), serviceKey);
}
原因找到就好半了,翻看源码,一步步找到IServiceProvider.GetRequiredKeyedService最终调用的接口方法然后再mocke即可
首先看下requiredServiceSupportingProvider.GetRequiredKeyedService(serviceType, serviceKey)调的是什么方法
/// <summary>
/// IKeyedServiceProvider is a service provider that can be used to retrieve services using a key in addition
/// to a type.
/// </summary>
public interface IKeyedServiceProvider : IServiceProvider
{
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <param name="serviceKey">An object that specifies the key of service object to get.</param>
/// <returns> A service object of type serviceType. -or- null if there is no service object of type serviceType.</returns>
object? GetKeyedService(Type serviceType, object? serviceKey);
/// <summary>
/// Gets service of type <paramref name="serviceType"/> from the <see cref="IServiceProvider"/> implementing
/// this interface.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <param name="serviceKey">The <see cref="ServiceDescriptor.ServiceKey"/> of the service.</param>
/// <returns>A service object of type <paramref name="serviceType"/>.
/// Throws an exception if the <see cref="IServiceProvider"/> cannot create the object.</returns>
object GetRequiredKeyedService(Type serviceType, object? serviceKey);
}
可以看到IKeyedServiceProvider也是继承了IServiceProvider接口,这就更好办了,我们直接Mock IKeyedServiceProvider并Setup即可,将用到IServiceProvider的地方,换成IKeyedServiceProvider,代码如下:
var serviceProvider = new Mock<IKeyedServiceProvider>();
serviceProvider.Setup(x => x.GetRequiredKeyedService(It.IsAny<AAA>(), It.IsAny<BBB>())).Returns(new CCC());
运行测试,完美。
总结
解决这个问题并不困难,但是如果.Net不开源,看不到源代码,还是有点头疼。
.NET 8 Moq mock GetRequiredKeyedService Setup报错的更多相关文章
- cap deploy:setup报错
今天部署cap的时候,setup出现以下错误: 查询半天未果,不过最后还是在google找到了,可见度娘极为不靠谱! I had the same error on deploy:setup with ...
- Mac Mojave(10.14.1)执行Matlab的mex报错
先装了matlab2018b,发现很频繁的crash,同时考虑到要跑的代码在>=2017a时就计算错误,于是转战matlab2016b matlab2016b安装后,执行mex -setup报错 ...
- Selenium Grid 运行报错 Exception thrown in Navigator.Start first time ->Error forwarding the new session Empty pool of VM for setup Capabilities
Selenium Grid 运行报错 : Exception thrown in Navigator.Start first time ->Error forwarding the new se ...
- python setup.py install 报错ImportError: No module named setuptools
学习光荣之路python课程时,使用python setup.py install安装其他模块时,第一次安装某模块成功了.安装另一模块却报错ImportError: No module named s ...
- pip安装mysql-python报错:Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-enRreC/mysql-python/
公司业务开发,用python开发网站;需要使用模块MySQLdb. 我直接pip install MySQLdb,当然不成功了,模块名字因该是mysql-python pip install mysq ...
- python pip install 报错TypeError: unsupported operand type(s) for -=: 'Retry' and 'int' Command "python setup.py egg_info" failed with error code 1 in
pip install http://download.pytorch.org/whl/cu80/torch-0.2.0.post3-cp27-cp27mu-manylinux1_x86_64.whl ...
- mock测试SpringMVC controller报错
使用mock测试Controller时报错如下 java.lang.NoClassDefFoundError: javax/servlet/SessionCookieConfig at org.spr ...
- python setup.py install 报错:error: [WinError 3] 系统找不到指定的路径。: 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\PlatformSDK\\lib
Outline 在通过 setup.py 安装python模块时,遇到了以下报错: # 执行 python setup.py install # 报错: error: [WinError 3] 系统找 ...
- python setup.py install 报错
python setup.py install 报错信息 [root@VM_25_28_centos psutil-2.0.0]# python setup.py install running in ...
- python下pip 安装 pyautogui报错Command "python setup.py egg_info" failed with error code 1 in C:\Users\Administrator\AppData\Local\Temp\pip-install-svhtepho\pygetwindow\
python装的3.6 64位,使用命令pip install pyautogui 或者pip install -U pyautogui 都失败了 报错如下: Command "python ...
随机推荐
- 使用64位Office2016处理万级数据的过程
先放下载和安装教程https://mp.weixin.qq.com/s/5ym9950_NZROlN0s2ZmLTg 由于同事电脑在使用Mysql for Excel插件处理十万级数据,如下图: 爆出 ...
- 制作visual studio 离线安装包
应用场景:脱机.内网环境安装vs开发环境. 概述:在互联网环境下载安装工具,下载根据需求并缓存布局(类似功能模块),压缩缓存内容拷贝至离线环境进行安装. 1.官网下载指定版本的vs安装客户端 创建基于 ...
- 韦东山freeRTOS系列教程之【第三章】任务管理
目录 系列教程总目录 概述 3.1 基本概念 3.2 任务创建与删除 3.2.1 什么是任务 3.2.2 创建任务 3.2.3 示例1: 创建任务 3.2.4 示例2: 使用任务参数 3.2.5 任务 ...
- 最简GIF解析代码gif_jumper,用于stb_image的小改进
gif jumper gif支持多帧动画,但是没有存储总帧数,解析gif直到结束才能知道总帧数. 所以gif解析代码,要么采用链表,要么不停realloc()分配内存,stb_image的代码就是如此 ...
- 微软账号密码修改后提示密码错误的解决方法(远程桌面&smb共享访问等)
众所周知,自从微软将Microsoft账户与Windows账号强制绑定后,使用起来便一直有诸多困难,在Microsoft Support和搜索引擎长期搜索解决方案未果,今天偶然在一个佬的博客翻到了这个 ...
- elementplus弹窗可拖拽draggable,点击空白处不消失close-on-click-modal,modal是否去掉遮罩层
<el-dialog :modal="false" v-model="dialogVisible" title="" width=&q ...
- [oeasy]python00134_[趣味拓展]python起源_历史_Guido人生_ABC编程语言_Tanenbaum
python 历史 回忆上次内容 颜文字是kaomoji 把字符变成一种图画的方法 一层叠一层 很多好玩儿的kaomoji是一层层堆叠起来的meme 添加图片注释,不超过 140 字(可选 ...
- 如何在 Vue 和 JavaScript 中截取视频任意帧图片
如何在 Vue 和 JavaScript 中截取视频任意帧图片 大家好!今天我们来聊聊如何在 Vue 和 JavaScript 中截取视频的任意一帧图片.这个功能在很多场景下都非常有用,比如视频编辑. ...
- 前端太卷了,不玩了,写写node.js全栈涨工资,赶紧学起来吧!!!!!
首先聊下node.js的优缺点和应用场景 Node.js的优点和应用场景 Node.js作为后端开发的选择具有许多优点,以下是其中一些: 高性能: Node.js采用了事件驱动.非阻塞I/O模型,使得 ...
- CCF 命令行选项
题目原文 问题描述(题目链接登陆账号有问题,要从这个链接登陆,然后点击"模拟考试",进去找本题目) 试题编号: 201403-3 试题名称: 命令行选项 时间限制: 1.0s ...