unit-testing - 如何使用Moq来模拟StackExchange.Redis库抛出的异常?

标签 unit-testing moq stackexchange.redis

我正在开发一个项目,我想使用 StackExchange.Redis 库连接到 Redis 数据库。此外,我想在单元测试中使用 Moq 作为模拟库,但我遇到了障碍,需要一些帮助来解决。

我的具体问题是,我有一个命令/响应架构,我正在尝试测试一个缓存“包装器”,该包装器在执行实际工作以返回响应之前检查缓存是否可以满足命令。一个重要的考虑因素是,缓存故障永远不应该阻止请求的处理,因此我想模拟 StackExchange.Redis IDatabase 接口(interface)的某些故障。但是,我似乎无法弄清楚如何从我的模拟对象中抛出 RedisException。例如,我只想使用以下代码,但它无法编译,因为没有用于该库引发的异常的公共(public)构造函数。

    Mock<IDatabase> _mockCache = new Mock<IDatabase>();

    // Simulate a connection exception to validate how the cache layer handles it
    //  THIS DOESN'T COMPILE THOUGH
    //
    _mockCache.Setup(cache => cache.StringGetAsync("a", CommandFlags.None)).Throws<RedisException>();

是否有更好的方法来模拟 StackExchange.Redis 库中的故障?我觉得我遗漏了一些明显的东西,要么是 Moq,要么是如何针对这个库进行测试。

最佳答案

您始终可以使用FormatterServices.GetUninitializedObject创建类的实例而不运行任何构造函数:

Creates a new instance of the specified object type.

Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object. The current method should only be used for deserialization when the user intends to immediately populate all fields. It does not create an uninitialized string, since creating an empty instance of an immutable type serves no purpose.

所以你的设置可能如下所示:

var e = (RedisException)FormatterServices.GetUninitializedObject(typeof(RedisException)); 

Mock<IDatabase> _mockCache = new Mock<IDatabase>();
_mockCache.Setup(cache => cache.StringGetAsync("a", CommandFlags.None)).Throws(e);

这有点骇人听闻;由于没有运行构造函数,因此您不应依赖 RedisException 实例的有效状态。

关于unit-testing - 如何使用Moq来模拟StackExchange.Redis库抛出的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28312183/

相关文章:

java - 编写第一个 JUnit 测试

c# - NSubstitute 使用一个类的真实实例作为替代,除了一个方法

session - StackExchange RedisTimeoutException

redis - 在 Centos 上运行多个 Redis 实例

java - Mockito "when"的可能性

unit-testing - dotnet 核心的无约束隔离(模拟)框架

c# - 如何在 C#.NET 中使用 Moq 模拟在单次调用中多次调用的方法?

c# - Moq 在被测试的方法中创建的对象

unit-testing - 模拟 IoC 容器?

redis - 如何找到具有特定成员值的Key?