c# - 具有只读 Prop 和内部构造函数的返回类型的模拟第三方接口(interface)

标签 c# unit-testing .net-core mocking moq

我正在尝试模拟我正在使用的第三方接口(interface) ( EventStore ClientAPI/IEventStoreConnection ),特别是这个方法:

Task<StreamEventsSlice> ReadStreamEventsForwardAsync(string stream, long start, int count, bool resolveLinkTos, UserCredentials userCredentials = null);

我遇到的问题是返回类型 StreamEventsSlicereadonly 字段和一个 internal 构造函数,即

public class StreamEventsSlice
{
    public readonly string Stream;
    //other similar fields

    internal StreamEventsSlice(string stream) //missing other fields
    {
        Stream = stream;
    }
}

在我的测试代码中,我使用 Moq 模拟事件存储连接,设置 ReadStreamEventsForwardAsyncMethod,并尝试像这样设置返回类型:

var connection = new Mock<IEventStoreConnection>();
connection.Setup(s => s.ReadStreamEventsForwardAsync(It.IsAny<string>(), It.IsAny<long>(), It.IsAny<int>(), It.IsAny<bool>(), It.IsAny<UserCredentials>())
    .ReturnsAsync(new StreamsEventSlice { props here });

但是我不能设置属性,或者调用构造函数而不是那个(我实际上只需要设置两个属性)

我试过制作一个扩展原始类的 stub ,然后返回它。尽管我可以隐藏只读属性,但我在类上收到一条错误消息,提示“StreamEventsSlice 没有采用 0 个参数的构造函数”。给它一个构造函数是行不通的,因为我不能调用基本构造函数,因为它是内部构造函数。

当我无法实例化返回类型时,如何模拟接口(interface)上的方法?

最佳答案

@MindSwipe 链接了两个很好的答案,不幸的是我不能使用 this one for constructing an object作为构造函数的参数之一也设置为内部。相反,我不得不使用 this method ,并使用他们的其他建议来设置属性。

我保持大部分模拟设置代码相同,除了添加和使用以下方法来实例化 StreamEventsSlice

internal StreamEventsSlice GetStreamEventSlice(ResolvedEvent[] events = null, bool isEndOfStream = true)
{
    events = events ?? new ResolvedEvent[0];
    var type = typeof(StreamEventsSlice);
    var slice = (StreamEventsSlice) FormatterServices.GetUninitializedObject(type);
    type.GetField("Events").SetValue(slice, events);
    type.GetField("IsEndOfStream").SetValue(slice, isEndOfStream);

    return slice;
}

关于c# - 具有只读 Prop 和内部构造函数的返回类型的模拟第三方接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57725084/

相关文章:

c# - PC 重新启动后,Visual Studio 有时会重建未修改的项目

c# - 在 OOP 中表达类型组合

c# - 单元测试 HttpContext.Current.Cache 或 C# 中的其他服务器端方法?

unit-testing - MSTest 和 NUnit 相比有哪些优势/劣势?

.net - 从 VS 2017 .NET Core 项目中的发布目录中排除文件

c# - 有选择地隐藏 C# 图表中的系列

c# - NerdDinner MVC4 版本 - 为什么他们删除了存储库类?

unit-testing - 我们如何测试构建 R 包时未公开的函数?

.net-core - Windows 和 Linux 上的 Net Core Worker 服务

c# - Blazor onclick 事件从循环中传入计数器