如何使用Moq模拟StackExchange.Redis ConnectionMultiplexer类? [英] How to use Moq to mock up the StackExchange.Redis ConnectionMultiplexer class?

查看:70
本文介绍了如何使用Moq模拟StackExchange.Redis ConnectionMultiplexer类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力模拟与StackExchange.Redis库有关的行为,但无法弄清楚如何正确模拟它使用的密封类.一个具体的示例是在我的调用代码中,我正在执行以下操作:

I am working to mock up behaviors related to the StackExchange.Redis library, but can't figure out how to properly mock the sealed classes it uses. A specific example is in my calling code I'm doing something like this:

    var cachable = command as IRedisCacheable;

    if (_cache.Multiplexer.IsConnected == false)
    {
        _logger.Debug("Not using the cache because the connection is not available");

        cacheAvailable = false;
    }
    else if (cachable == null)
    {

其中的关键行是 _cache.Multiplexer.IsConnected ,在使用缓存之前,我要检查该行以确保我具有有效的连接.因此,在我的测试中,我想使用以下类似方法来模拟这种行为:

The key line in there is _cache.Multiplexer.IsConnected where I'm checking to make sure I have a valid connection before using the cache. So in my tests I want to mock up this behavior with something like this:

    _mockCache = new Mock<IDatabase>();
    _mockCache.Setup(cache => cache.Multiplexer.IsConnected).Returns(false);

但是,尽管该代码可以正常编译,但是在运行测试时却出现此错误:

However, while that code compiles just fine, I get this error when running the test:

我也尝试过模拟多路复用器类本身,并将其提供给模拟的缓存,但是我遇到了这样一个事实,即多路复用器类是密封的:

I have also tried mocking the multiplexer class itself, and providing that to my mocked cache, but I run into the fact the multiplexer class is sealed:

    _mockCache = new Mock<IDatabase>();
    var mockMultiplexer = new Mock<ConnectionMultiplexer>();
    mockMultiplexer.Setup(c => c.IsConnected).Returns(false);
    _mockCache.Setup(cache => cache.Multiplexer).Returns(mockMultiplexer.Object);

...但是会导致此错误:

...but that results in this error:

最终,我想在测试中控制该属性是true还是false,那么有没有一种正确的方法来模拟这样的事情?

Ultimately I want to control whether that property is true or false in my tests, so is there a correct way to mock up something like this?

推荐答案

我认为最好的方法是将所有Redis交互包装在您自己的类和接口中.类似于 CacheHandler:ICacheHandler ICacheHandler .您所有的代码只会和 ICacheHandler 说话.

The best approach in my opinion is to wrap all of your Redis interaction in your own class and interface. Something like CacheHandler : ICacheHandler and ICacheHandler. All of your code would only ever speak to ICacheHandler.

这样,您消除了对Redis的严格依赖(可以随意替换 ICacheHandler 的实现).您还可以模拟与缓存层的所有交互,因为它是针对接口编程的.

This way, you eliminate a hard dependency on Redis (you can swap out the implementation of ICacheHandler as you please). You can also mock all interaction with your caching layer because it's programmed against the interface.

您不应该直接测试 StackExchange.Redis -这不是您编写的代码.

You should not test StackExchange.Redis directly - it is not code you've written.

这篇关于如何使用Moq模拟StackExchange.Redis ConnectionMultiplexer类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆