如何使用最小起订量模拟私有只读 IList 属性

本文关键字:IList 只读 属性 模拟 何使用 | 更新日期: 2023-09-27 18:31:22

我试图嘲笑这个列表:

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

使用这个(如此处所示):

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

但是在运行时,我得到一个无效的投射异常:

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

我做错了什么?

如何使用最小起订量模拟私有只读 IList<T> 属性

好吧,我认为嘲笑私有实现细节是奇怪且坦率错误的。测试不应依赖于私有实现详细信息。

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

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

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

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

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

,然后使用 Moq 覆盖该属性。

不过,你做错了。

您有一个字段,但尝试设置属性 get。

将myList更改为属性可以工作(这里不是最小起订量专家):

private readonly IList<MyClass> myListFiled = new List<MyClass>();
private IList<MyClass> myList {
  get 
   {return myListFiled;}
}