如何模拟私有的只读 IList<T>使用最小起订量的属性 [英] How to mock a private readonly IList<T> property using moq
本文介绍了如何模拟私有的只读 IList<T>使用最小起订量的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试模拟此列表:
I'm trying to mock this list:
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);
但是在运行时我得到一个 InvalidCastException:
However at runtime I get an InvalidCastException:
Unable to cast object of type 'System.Collections.Generic.List`1[MyClass]' to
type 'System.Collections.ObjectModel.ReadOnlyCollection`1[MyClass]'.
我做错了什么?
推荐答案
好吧,我认为模拟私有实现细节很奇怪,而且坦率地说是错误的.您的测试不应依赖于私有实现细节.
但如果我是你,我会这样做的方法是添加一个构造函数:
But the way that I'd do this if I were you is to add a constructor:
public Foo {
private readonly IList<MyClass> myList;
public Foo(IList<MyClass> myList) { this.myList = myList; }
}
然后使用 Moq 模拟 IList
的实例并通过构造函数传递它.
and then use Moq to mock an instance of IList<MyClass>
and pass that through the constructor.
如果你不喜欢这个建议,或者,创建一个虚拟财产:
If you don't like that suggestion, alternatively, make a virtual property:
public Foo {
private readonly IList<MyClass> myList = new MyList();
public virtual IList<MyClass> MyList { get { return this.myList; } }
}
然后使用 Moq 覆盖该属性.
and then use Moq to override that property.
你还是做错了.
这篇关于如何模拟私有的只读 IList<T>使用最小起订量的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文