【问题标题】:How to unit test Service Stacks Redis Client with Moq如何使用 Moq 对 Service Stacks Redis 客户端进行单元测试
【发布时间】:2015-01-23 07:59:41
【问题描述】:

我试图了解如何模拟 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);
    }

【问题讨论】:

  • 你尝试了什么?它奏效了吗?为什么不?你的想法是什么?
  • 编辑后的帖子 - 如果我能弄清楚如何正确模拟 GetClient() 方法应该没问题。
  • 很好。你可以试试mock.Setup(t =&gt; t.As&lt;Model.Property&gt;().GetClient()).Returns(instance);吗?

标签: unit-testing servicestack moq servicestack.redis


【解决方案1】:

总之,既然RedisClient实现了IRedisClient,那你有没有尝试使用接口来创建mock?

 var instance = new Mock<IRedisClient>();

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

var target= new PropertyCommandHandler(mock);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-09
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 2012-06-01
    • 2014-12-30
    相关资源
    最近更新 更多