?,c#,nunit,moq"/>

首页 > 解决方案 > 如何模拟 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?

任何线索表示赞赏

标签: c#nunitmoq

解决方案


我建议添加一个重载的构造函数:

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

推荐阅读