gpt4 book ai didi

c# - 如何使用最小起订量模拟私有(private)只读 IList 属性

转载 作者:行者123 更新时间:2023-12-03 21:50:41 24 4
gpt4 key购买 nike

我正在尝试模拟这个列表:

private readonly IList<MyClass> myList = new List<MyClass>();

使用它(如 here 所示):

IList<MyClass> mockList = Builder<MyClass>.CreateListOfSize(5).Build();
mockObj.SetupGet<IEnumerable<MyClass>>(o => o.myList).Returns(stakeHoldersList);

但是在运行时我得到一个 InvalidCastException:

Unable to cast object of type 'System.Collections.Generic.List`1[MyClass]' to
type 'System.Collections.ObjectModel.ReadOnlyCollection`1[MyClass]'.

我做错了什么?

最佳答案

好吧,我认为模拟私有(private)实现细节很奇怪而且坦率地说是错误的。您的测试不应依赖于私有(private)实现细节。

但是如果我是你,我会这样做的方式是添加一个构造函数:

public Foo {
private readonly IList<MyClass> myList;
public Foo(IList<MyClass> myList) { this.myList = myList; }
}

然后使用 Moq 模拟 IList<MyClass> 的实例并将其传递给构造函数。

如果您不喜欢该建议,或者创建一个虚拟属性(property):

public Foo {
private readonly IList<MyClass> myList = new MyList();
public virtual IList<MyClass> MyList { get { return this.myList; } }
}

然后使用 Moq 覆盖该属性。

仍然,您做错了。

关于c# - 如何使用最小起订量模拟私有(private)只读 IList<T> 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10197819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com