如何使用Moq对Service Stacks Redis Client进行单元测试

迈克·W

我试图了解如何模拟IRedisClientsManager,以便可以使用Moq对下面的Handle方法进行单元测试。

干杯

 public class PropertyCommandHandler : ICommandHandlerFor<PropertySaveRequest, PropertyCommandResult>
{
    private readonly IRedisClientsManager _manager;

    public PropertyCommandHandler(IRedisClientsManager manager)
    {
        this._manager = manager;
    }

    public PropertyCommandResult Handle(PropertySaveRequest request)
    {
        request.Property.OwnerId.ValidateArgumentRange();

        using (var client =_manager.GetClient())
        {
            var propertyClient = client.As<Model.Property>();

            var propertyKey = string.Format("property:{0}", request.Property.OwnerId);

            propertyClient.SetEntry(propertyKey, request.Property);

            client.AddItemToSet("property", request.Property.OwnerId.ToString());
        }

        return new PropertyCommandResult() {Success = true};
    }
}

我从服务中这样打电话

public class PropertyService : Service, IPropertyService
{
    private readonly ICommandHandlerFor<PropertySaveRequest, PropertyCommandResult> _commandHandler;

    public PropertyService(ICommandHandlerFor<PropertySaveRequest, PropertyCommandResult> commandHandler)
    {
        this._commandHandler = commandHandler;
    }

    public object Post(PropertySaveRequest request)
    {
        if (request.Property == null)
            throw new HttpError(HttpStatusCode.BadRequest, "Property cannot be null");

        var command = _commandHandler.Handle(request);
        return command;
    }
}

到目前为止,这是方法-不确定是否步入正轨

    [Test]
    public void TestMethod1()
    {
        //arrange
        _container = new WindsorContainer()
                .Install(new PropertyInstaller());

        var mock = new Mock<IRedisClientsManager>();
        var instance = new Mock<RedisClient>();
        mock.Setup(t => t.GetClient()).Returns(instance);
        // cannot resolve method error on instance
        // stuck ...
        var service = _container.Resolve<IPropertyService>(mock);
    }
克里索

简而言之,由于RedisClient实现了IRedisClient,您是否尝试使用该接口创建模拟?

 var instance = new Mock<IRedisClient>();

为什么要使用真实的容器进行单元测试?您应该使用自动模拟容器,或者简单地(因为您已经在手动处理模拟)创建测试目标的真实实例,以提供模拟作为依赖项

var target= new PropertyCommandHandler(mock);

顺便说一句,恕我直言,返回值的“命令处理程序”听起来像是一种气味。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章