c# - 如何模拟 Func?
问题描述
我有如下服务方法。我正在尝试模拟测试方法
public class A
{
private readonly IHandler createDeviceContentStatus;
private readonly IHandler updateDeviceContentStatus;
public A(Func<Type, IHandler> handlerFactory)
{
this.createDeviceContentStatus = handlerFactory(typeof(CreateDCS));
this.updateDeviceContentStatus =
handlerFactory(typeof(UpdateDeviceContentStatus));
}
}
如何A
在测试方法中为类构造函数创建 Mock?
任何线索表示赞赏
解决方案
我建议添加一个重载的构造函数:
public class A
{
private readonly IHandler createDeviceContentStatus;
private readonly IHandler updateDeviceContentStatus;
public A(Func<Type, IHandler> handlerFactory)
: this(handlerFactory(typeof(CreateDCS)), handlerFactory(typeof(UpdateDeviceContentStatus)))
{
}
public A(IHandler createDeviceContentStatus, IHandler updateDeviceContentStatus)
{
this.createDeviceContentStatus = createDeviceContentStatus;
this.updateDeviceContentStatus = updateDeviceContentStatus;
}
}
然后嘲笑将很容易:
Mock<IHandler> createDeviceMock = new Mock<IHandler>();
Mock<IHandler> updateDeviceMock = new Mock<IHandler>();
// setup the mocks
A a = new A(createDeviceMock.Object, updateDeviceMock.Object);
如果您不想创建此构造函数,请创建一个返回模拟的 lambda:
Mock<IHandler> createDeviceMock = new Mock<IHandler>();
Mock<IHandler> updateDeviceMock = new Mock<IHandler>();
// setup the mocks
Func<Type,IHandler> factory = (t) =>
{
if(t == typeof(CreateDCS)) return createDeviceMock.Object;
if(t == typeof(UpdateDeviceContentStatus)) return updateDeviceMock.Object;
throw new ArgumentException();
};
A a = new A(factory);
推荐阅读
- javascript - jQuery 将输入值附加到 iframe data-src
- php - 使用 Sendgrid 3.5.1 API、PHP 发送附件
- javascript - hasAttribute("Role") 崩溃网页
- jenkins - 如何将地图传递给詹金斯groovy管道中的变量
- javascript - 如何将数据从 Rails 6 传递到 JavaScript
- freetds - IBM i Python 使用 FreeTDS 连接到 MS SQL
- r - 使用 base r 获取外部图像文件尺寸
- intellij-idea - 有没有办法在 IntelliJ 中删除 jacoco 分支覆盖
- c# - 当用户从下拉列表中选择货币时,货币会恢复
- r - 计算 r 中阈值以下的持续时间