模拟一个 returns 只读结构的接口方法

Mock an interface method that returns a read only struct

我正在尝试在接口上模拟一个方法,该接口 returns 是一个具有内部构造函数的只读结构。由于我需要我的模拟响应在对象中具有某些值,如何才能实现这一点?我正在使用 XUnit 和 Moq。

使用redis堆栈交换库的工作示例;这个界面IDatabase has a method StreamGroupInfo and the response object is StreamGroupInfo。此响应对象是具有内部构造函数的只读结构,因此我不能简单地创建该对象的实例并分配我想要的值。

您可以使用Activator.CreateInstance

// Arguments to pass to internal constructor here in order
var args = new object[] { "name", 10, 20, "someId" };
// You need to leave the (Binder) and (CultureInfo) casts so that C# compiler would call the correct overload for Activator.CreateInstance
var obj = (StreamGroupInfo)Activator.CreateInstance(typeof(StreamGroupInfo), BindingFlags.NonPublic | BindingFlags.Instance, (Binder)null, args, (CultureInfo)null);

请注意,在上面的代码中,有两个类型转换似乎是不必要的(Visual Studio 会建议您删除它们)。但由于参数的值为空,C# 无法知道参数类型。因此它将采用 Object 类型并将调用 Activator.CreateInstance(Type type, params object[] args) 重载,这将不起作用。您可以按如下方式重写代码以沉默 Visual Studio 建议您删除强制转换,它只是额外的两个 lines/variables.

// Arguments to pass to internal constructor here in order
var args = new object[] { "name", 10, 20, "someId" };
Binder binder = null;
CultureInfo culture = null;
var obj = (StreamGroupInfo)Activator.CreateInstance(typeof(StreamGroupInfo), BindingFlags.NonPublic | BindingFlags.Instance, binder, args, culture);